(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DUIX = factory()); })(this, (function () { 'use strict'; function _mergeNamespaces(n, m) { m.forEach(function (e) { e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); }); return Object.freeze(n); } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _regeneratorRuntime() { _regeneratorRuntime = function () { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function (obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return { value: void 0, done: !0 }; } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable || "" === iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } throw new TypeError(typeof iterable + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function (skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function () { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function (exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function (type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function (record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function (finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function (tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function (iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableRest() { 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 _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; } function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } } function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var AgoraRTC_NProduction = {exports: {}}; (function(module,exports){!function(e,t){module.exports=t();}(commonjsGlobal,function(){function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i];}});}});}),Object.freeze(e);}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;}var n=function(e){try{return !!e();}catch(e){return !0;}},r=!n(function(){var e=function(){}.bind();return "function"!=typeof e||e.hasOwnProperty("prototype");}),s=r,o=Function.prototype,a=o.call,c=s&&o.bind.bind(a,a),d=s?c:function(e){return function(){return a.apply(e,arguments);};},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math==Math&&e;},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||function(){return this;}()||t||Function("return this")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments);}),g=d,T=g({}.toString),S=g("".slice),R=function(e){return S(T(e),8,-1);},C=R,I=d,v=function(e){if("Function"===C(e))return I(e);},y="object"==typeof document&&document.all,A={all:y,IS_HTMLDDA:void 0===y&&void 0!==y},b=A.all,w=A.IS_HTMLDDA?function(e){return "function"==typeof e||e===b;}:function(e){return "function"==typeof e;},O={},N=!n(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7;}})[1];}),D=r,P=Function.prototype.call,L=D?P.bind(P):function(){return P.apply(P,arguments);},k={},M={}.propertyIsEnumerable,U=Object.getOwnPropertyDescriptor,x=U&&!M.call({1:2},1);k.f=x?function(e){var t=U(this,e);return !!t&&t.enumerable;}:M;var V,F,B=function(e,t){return {enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t};},j=n,G=R,W=Object,H=d("".split),K=j(function(){return !W("z").propertyIsEnumerable(0);})?function(e){return "String"==G(e)?H(e,""):W(e);}:W,Y=function(e){return null==e;},q=Y,z=TypeError,J=function(e){if(q(e))throw z("Can't call method on "+e);return e;},X=K,Q=J,Z=function(e){return X(Q(e));},$=w,ee=A.all,te=A.IS_HTMLDDA?function(e){return "object"==typeof e?null!==e:$(e)||e===ee;}:function(e){return "object"==typeof e?null!==e:$(e);},ie={},ne=ie,re=h,se=w,oe=function(e){return se(e)?e:void 0;},ae=function(e,t){return arguments.length<2?oe(ne[e])||oe(re[e]):ne[e]&&ne[e][t]||re[e]&&re[e][t];},ce="undefined"!=typeof navigator&&String(navigator.userAgent)||"",de=h,le=ce,ue=de.process,he=de.Deno,pe=ue&&ue.versions||he&&he.version,_e=pe&&pe.v8;_e&&(F=(V=_e.split("."))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&le&&(!(V=le.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=le.match(/Chrome\/(\d+)/))&&(F=+V[1]);var Ee=F,me=Ee,fe=n,ge=h.String,Te=!!Object.getOwnPropertySymbols&&!fe(function(){var e=Symbol();return !ge(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&me&&me<41;}),Se=Te&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Re=ae,Ce=w,Ie=l,ve=Object,ye=Se?function(e){return "symbol"==typeof e;}:function(e){var t=Re("Symbol");return Ce(t)&&Ie(t.prototype,ve(e));},Ae=String,be=function(e){try{return Ae(e);}catch(e){return "Object";}},we=w,Oe=be,Ne=TypeError,De=function(e){if(we(e))return e;throw Ne(Oe(e)+" is not a function");},Pe=De,Le=Y,ke=function(e,t){var i=e[t];return Le(i)?void 0:Pe(i);},Me=L,Ue=w,xe=te,Ve=TypeError,Fe={exports:{}},Be=h,je=Object.defineProperty,Ge=function(e,t){try{je(Be,e,{value:t,configurable:!0,writable:!0});}catch(i){Be[e]=t;}return t;},We="__core-js_shared__",He=h[We]||Ge(We,{}),Ke=He;(Fe.exports=function(e,t){return Ke[e]||(Ke[e]=void 0!==t?t:{});})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Ye=Fe.exports,qe=J,ze=Object,Je=function(e){return ze(qe(e));},Xe=Je,Qe=d({}.hasOwnProperty),Ze=Object.hasOwn||function(e,t){return Qe(Xe(e),t);},$e=d,et=0,tt=Math.random(),it=$e(1..toString),nt=function(e){return "Symbol("+(void 0===e?"":e)+")_"+it(++et+tt,36);},rt=Ye,st=Ze,ot=nt,at=Te,ct=Se,dt=h.Symbol,lt=rt("wks"),ut=ct?dt.for||dt:dt&&dt.withoutSetter||ot,ht=function(e){return st(lt,e)||(lt[e]=at&&st(dt,e)?dt[e]:ut("Symbol."+e)),lt[e];},pt=L,_t=te,Et=ye,mt=ke,ft=function(e,t){var i,n;if("string"===t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;if(Ue(i=e.valueOf)&&!xe(n=Me(i,e)))return n;if("string"!==t&&Ue(i=e.toString)&&!xe(n=Me(i,e)))return n;throw Ve("Can't convert object to primitive value");},gt=TypeError,Tt=ht("toPrimitive"),St=function(e,t){if(!_t(e)||Et(e))return e;var i,n=mt(e,Tt);if(n){if(void 0===t&&(t="default"),i=pt(n,e,t),!_t(i)||Et(i))return i;throw gt("Can't convert object to primitive value");}return void 0===t&&(t="number"),ft(e,t);},Rt=ye,Ct=function(e){var t=St(e,"string");return Rt(t)?t:t+"";},It=te,vt=h.document,yt=It(vt)&&It(vt.createElement),At=function(e){return yt?vt.createElement(e):{};},bt=At,wt=!N&&!n(function(){return 7!=Object.defineProperty(bt("div"),"a",{get:function(){return 7;}}).a;}),Ot=N,Nt=L,Dt=k,Pt=B,Lt=Z,kt=Ct,Mt=Ze,Ut=wt,xt=Object.getOwnPropertyDescriptor;O.f=Ot?xt:function(e,t){if(e=Lt(e),t=kt(t),Ut)try{return xt(e,t);}catch(e){}if(Mt(e,t))return Pt(!Nt(Dt.f,e,t),e[t]);};var Vt=n,Ft=w,Bt=/#|\.prototype\./,jt=function(e,t){var i=Wt[Gt(e)];return i==Kt||i!=Ht&&(Ft(t)?Vt(t):!!t);},Gt=jt.normalize=function(e){return String(e).replace(Bt,".").toLowerCase();},Wt=jt.data={},Ht=jt.NATIVE="N",Kt=jt.POLYFILL="P",Yt=jt,qt=De,zt=r,Jt=v(v.bind),Xt=function(e,t){return qt(e),void 0===t?e:zt?Jt(e,t):function(){return e.apply(t,arguments);};},Qt={},Zt=N&&n(function(){return 42!=Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype;}),$t=te,ei=String,ti=TypeError,ii=function(e){if($t(e))return e;throw ti(ei(e)+" is not an object");},ni=N,ri=wt,si=Zt,oi=ii,ai=Ct,ci=TypeError,di=Object.defineProperty,li=Object.getOwnPropertyDescriptor,ui="enumerable",hi="configurable",pi="writable";Qt.f=ni?si?function(e,t,i){if(oi(e),t=ai(t),oi(i),"function"==typeof e&&"prototype"===t&&"value"in i&&pi in i&&!i[pi]){var n=li(e,t);n&&n[pi]&&(e[t]=i.value,i={configurable:hi in i?i[hi]:n[hi],enumerable:ui in i?i[ui]:n[ui],writable:!1});}return di(e,t,i);}:di:function(e,t,i){if(oi(e),t=ai(t),oi(i),ri)try{return di(e,t,i);}catch(e){}if("get"in i||"set"in i)throw ci("Accessors not supported");return "value"in i&&(e[t]=i.value),e;};var _i=Qt,Ei=B,mi=N?function(e,t,i){return _i.f(e,t,Ei(1,i));}:function(e,t,i){return e[t]=i,e;},fi=h,gi=f,Ti=v,Si=w,Ri=O.f,Ci=Yt,Ii=ie,vi=Xt,yi=mi,Ai=Ze,bi=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e();case 1:return new e(i);case 2:return new e(i,n);}return new e(i,n,r);}return gi(e,this,arguments);};return t.prototype=e.prototype,t;},wi=function(e,t){var i,n,r,s,o,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?fi:p?fi[u]:(fi[u]||{}).prototype,m=h?Ii:Ii[u]||yi(Ii,u,{})[u],f=m.prototype;for(s in t)n=!(i=Ci(h?s:u+(p?".":"#")+s,e.forced))&&E&&Ai(E,s),a=m[s],n&&(c=e.dontCallGetSet?(l=Ri(E,s))&&l.value:E[s]),o=n&&c?c:t[s],n&&typeof a==typeof o||(d=e.bind&&n?vi(o,fi):e.wrap&&n?bi(o):_&&Si(o)?Ti(o):o,(e.sham||o&&o.sham||a&&a.sham)&&yi(d,"sham",!0),yi(m,s,d),_&&(Ai(Ii,r=u+"Prototype")||yi(Ii,r,{}),yi(Ii[r],s,o),e.real&&f&&(i||!f[s])&&yi(f,s,o)));},Oi=Math.ceil,Ni=Math.floor,Di=Math.trunc||function(e){var t=+e;return (t>0?Ni:Oi)(t);},Pi=function(e){var t=+e;return t!=t||0===t?0:Di(t);},Li=Pi,ki=Math.max,Mi=Math.min,Ui=function(e,t){var i=Li(e);return i<0?ki(i+t,0):Mi(i,t);},xi=Pi,Vi=Math.min,Fi=function(e){return e>0?Vi(xi(e),9007199254740991):0;},Bi=function(e){return Fi(e.length);},ji=Z,Gi=Ui,Wi=Bi,Hi=function(e){return function(t,i,n){var r,s=ji(t),o=Wi(s),a=Gi(n,o);if(e&&i!=i){for(;o>a;)if((r=s[a++])!=r)return !0;}else for(;o>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return !e&&-1;};},Ki={includes:Hi(!0),indexOf:Hi(!1)},Yi=Ki.includes;wi({target:"Array",proto:!0,forced:n(function(){return !Array(1).includes();})},{includes:function(e){return Yi(this,e,arguments.length>1?arguments[1]:void 0);}});var qi=ie,zi=function(e){return qi[e+"Prototype"];},Ji=zi("Array").includes,Xi=te,Qi=R,Zi=ht("match"),$i=function(e){var t;return Xi(e)&&(void 0!==(t=e[Zi])?!!t:"RegExp"==Qi(e));},en=TypeError,tn={};tn[ht("toStringTag")]="z";var nn="[object z]"===String(tn),rn=nn,sn=w,on=R,an=ht("toStringTag"),cn=Object,dn="Arguments"==on(function(){return arguments;}()),ln=rn?on:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t];}catch(e){}}(t=cn(e),an))?i:dn?on(t):"Object"==(n=on(t))&&sn(t.callee)?"Arguments":n;},un=ln,hn=String,pn=function(e){if("Symbol"===un(e))throw TypeError("Cannot convert a Symbol value to a string");return hn(e);},_n=ht("match"),En=wi,mn=function(e){if($i(e))throw en("The method doesn't accept regular expressions");return e;},fn=J,gn=pn,Tn=function(e){var t=/./;try{"/./"[e](t);}catch(i){try{return t[_n]=!1,"/./"[e](t);}catch(e){}}return !1;},Sn=d("".indexOf);En({target:"String",proto:!0,forced:!Tn("includes")},{includes:function(e){return !!~Sn(gn(fn(this)),gn(mn(e)),arguments.length>1?arguments[1]:void 0);}});var Rn=zi("String").includes,Cn=l,In=Ji,vn=Rn,yn=Array.prototype,An=String.prototype,bn=i(function(e){var t=e.includes;return e===yn||Cn(yn,e)&&t===yn.includes?In:"string"==typeof e||e===An||Cn(An,e)&&t===An.includes?vn:t;});let wn=!0,On=!0;function Nn(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10);}function Dn(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const s=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t));};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map()),this._eventMap[t].set(n,s),r.apply(this,[e,s]);};const s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(i))return s.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n]);},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t];},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e);},enumerable:!0,configurable:!0});}function Pn(e){return "boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(wn=e,e?"adapter.js logging disabled":"adapter.js logging enabled");}function Ln(e){return "boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(On=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"));}function kn(){if("object"==typeof window){if(wn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments);}}function Mn(e,t){On&&console.warn(e+" is deprecated, please use "+t+" instead.");}function Un(e){return "[object Object]"===Object.prototype.toString.call(e);}function xn(e){return Un(e)?Object.keys(e).reduce(function(t,i){const n=Un(e[i]),r=n?xn(e[i]):e[i],s=n&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[i]:r});},{}):e;}function Vn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?Vn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach(t=>{Vn(e,e.get(t),i);});}));}function Fn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map();if(null===t)return r;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e);}),s.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&Vn(e,i,r);});}),r;}const Bn=kn;function jn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t;};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e));}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e]);});}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t;},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio);}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return !o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Bn("chrome: "+JSON.stringify(e)),r(e);});}e.video=n(e.video);}return Bn("chrome: "+JSON.stringify(e)),r(e);},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message;}};};if(i.getUserMedia=function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(s(e));});});}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop();}),new DOMException("","NotFoundError");return e;},e=>Promise.reject(s(e))));};}}function Gn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream;}function Wn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack;},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e);},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r);});},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments);};}else Dn(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));}function Hn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return {track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf;},_pc:e};};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice();};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r;};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1);};}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e));});};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1);});};}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf;}});}}function Kn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(t=>{i[t]=e.stat(t);}),t[i.id]=i;}),t;},s=function(e){return new Map(Object.keys(e).map(t=>[t,e[t]]));};if(arguments.length>=2){const n=function(e){i(s(r(e)));};return t.apply(this,[n,e]);}return new Promise((e,i)=>{t.apply(this,[function(t){e(s(r(t)));},i]);}).then(i,n);};}function Yn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>Fn(t,e.track,!0));};}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),Dn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>Fn(t,e.track,!1));};}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i);}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"));}return t.apply(this,arguments);};}function qn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0]);};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n;};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError");});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n);};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments);};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t];}),r.apply(this,arguments);};}function zn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return qn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id]);};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError");}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i;}n.apply(this,[t]);};const r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id);}),new RTCSessionDescription({type:t.type,sdp:i});}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id];},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"));});else {const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n);}return this.getSenders().find(e=>e.track===t);},["createOffer","createAnswer"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=s(this,t);e[0].apply(null,[i]);},t=>{e[1]&&e[1].apply(null,t);},arguments[2]]):i.apply(this,arguments).then(e=>s(this,e));}};e.RTCPeerConnection.prototype[t]=n[t];});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id);}),new RTCSessionDescription({type:t.type,sdp:i});}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments);};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return ""===e.type?e:s(this,e);}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i]);}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")));};}function Jn(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});}function Xn(e,t){Dn(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e;});}var Qn=Object.freeze({__proto__:null,fixNegotiationNeeded:Xn,shimAddTrackRemoveTrack:zn,shimAddTrackRemoveTrackWithNative:qn,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i);});}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"));},shimGetSendersWithDtmf:Hn,shimGetStats:Kn,shimGetUserMedia:jn,shimMediaStream:Gn,shimOnTrack:Wn,shimPeerConnection:Jn,shimSenderReceiverGetStats:Yn});function Zn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Mn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n);},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t]);},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return "object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i);},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i;};}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return "audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i]);};}}}function $n(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return {receiver:this.receiver};}});}function er(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments);}};e.RTCPeerConnection.prototype[t]=n[t];});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type;});}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}));});}return e;}).then(r,s);};}function tr(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e;}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map());};}function ir(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e;}),Dn(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track);};}function nr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Mn("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t);});});}function rr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel);}function sr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0");});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings;}).catch(()=>{delete t.sendEncodings;})));}return n;});}function or(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return "encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e;});}function ar(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}function cr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[];}):t.apply(this,arguments);};}var dr=Object.freeze({__proto__:null,shimAddTransceiver:sr,shimCreateAnswer:cr,shimCreateOffer:ar,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e);}return !0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i);});},shimGetParameters:or,shimGetUserMedia:Zn,shimOnTrack:$n,shimPeerConnection:er,shimRTCDataChannel:rr,shimReceiverGetStats:ir,shimRemoveStream:nr,shimSenderGetStats:tr});function lr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams;}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e));},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e];}),t.apply(this,arguments);};}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e);});});}}function ur(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[];}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream;},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t);});});}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i);});}),t.apply(e,arguments);};}}function hr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r;},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r;};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;};t.setLocalDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n;},t.addIceCandidate=a;}function pr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(_r(e));}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n);}.bind(t));}function _r(e){return e&&void 0!==e.video?Object.assign({},e,{video:xn(e.video)}):e;}function Er(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;it.generateCertificate});}function mr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return {receiver:this.receiver};}});}function fr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"});}return t.apply(this,arguments);};}function gr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext);}var Tr=Object.freeze({__proto__:null,shimAudioContext:gr,shimCallbacksAPI:hr,shimConstraints:_r,shimCreateOfferLegacy:fr,shimGetUserMedia:pr,shimLocalStreamsAPI:lr,shimRTCIceServerUrls:Er,shimRemoteStreamsAPI:ur,shimTrackEventTransceiver:mr}),Sr={exports:{}};!function(e){const 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(e=>e.trim());},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n");},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0];},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i;},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i));},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e0?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){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t);}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n";}return t;},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return {type:t.shift(),parameter:t.join(" ")};},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n";}),t;},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i;},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return {semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))};},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6);},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return {algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()};},t.getDtlsParameters=function(e,i){return {role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)};},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n";}),i;},t.parseCryptoLine=function(e){const t=e.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"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n";},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.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,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine);},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null;},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t;},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r{i.headerExtensions.push(t.parseExtmap(e));});const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t);});}),i;},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e);});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime);}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e);}),n;},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},i.push(t));}}),0===i.length&&a&&i.push({ssrc:a});let 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,i.forEach(e=>{e.maxBitrate=l;})),i;},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i;},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t;},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0;},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return {port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return {port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r};}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("");},t.generateSessionId=function(){return Math.random().toString().substr(2,22);},t.writeSessionBoilerplate=function(e,i,n){let r;const s=void 0!==i?i:2;r=e||t.generateSessionId();return "v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n";},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t));}function yr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Dn(e,"icecandidate",e=>{if(e.candidate){const t=Cr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24]);}return e;});}function Ar(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp;}});const i=function(e){if(!e||!e.sdp)return !1;const t=Cr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Cr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP");});},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;const i=parseInt(t[1],10);return i!=i?-1:i;},r=function(e){let i=65536;return "firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i;},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Cr.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n;},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp;},enumerable:!0,configurable:!0});}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=s(arguments[0],e);let o;o=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a;}return o.apply(this,arguments);};}function br(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments);};}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e;},Dn(e,"datachannel",e=>(t(e.channel,e.target),e));}function wr(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return {completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState;},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null;},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e);},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i);}return e;},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments);};});}function Or(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i;}return i.apply(this,arguments);};}function Nr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve());});}function Dr(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer";}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return ("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]));});}var Pr=Object.freeze({__proto__:null,removeExtmapAllowMixed:Or,shimAddIceCandidateNullOrEmpty:Nr,shimConnectionState:wr,shimMaxMessageSize:Ar,shimParameterlessSetLocalDescription:Dr,shimRTCIceCandidate:vr,shimRTCIceCandidateRelayProtocol:yr,shimSendThrowTypeError:br});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=kn,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=Nn(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Nn(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else {if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Nn(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype;}return t;}(e),r={browserDetails:n,commonShim:Pr,extractVersion:Nn,disableLog:Pn,disableWarnings:Ln,sdp:Ir};switch(n.browser){case"chrome":if(!Qn||!Jn||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Qn,Nr(e,n),Dr(e),jn(e,n),Gn(e),Jn(e,n),Wn(e),zn(e,n),Hn(e),Kn(e),Yn(e),Xn(e,n),vr(e),yr(e),wr(e),Ar(e,n),br(e),Or(e,n);break;case"firefox":if(!dr||!er||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=dr,Nr(e,n),Dr(e),Zn(e,n),er(e,n),$n(e),nr(e),tr(e),ir(e),rr(e),sr(e),or(e),ar(e),cr(e),vr(e),wr(e),Ar(e,n),br(e);break;case"safari":if(!Tr||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Tr,Nr(e,n),Dr(e),Er(e),fr(e),hr(e),lr(e),ur(e),mr(e),pr(e),gr(e),vr(e),yr(e),Ar(e,n),br(e),Or(e,n);break;default:i("Unsupported browser!");}}({window:"undefined"==typeof window?void 0:window});var Lr={exports:{}},kr=wi,Mr=N,Ur=Qt.f;kr({target:"Object",stat:!0,forced:Object.defineProperty!==Ur,sham:!Mr},{defineProperty:Ur});var xr=ie.Object,Vr=Lr.exports=function(e,t,i){return xr.defineProperty(e,t,i);};xr.defineProperty.sham&&(Vr.sham=!0);var Fr=i(Lr.exports),Br=R,jr=Array.isArray||function(e){return "Array"==Br(e);},Gr=TypeError,Wr=Ct,Hr=Qt,Kr=B,Yr=function(e,t,i){var n=Wr(t);n in e?Hr.f(e,n,Kr(0,i)):e[n]=i;},qr=w,zr=He,Jr=d(Function.toString);qr(zr.inspectSource)||(zr.inspectSource=function(e){return Jr(e);});var Xr=zr.inspectSource,Qr=d,Zr=n,$r=w,es=ln,ts=Xr,is=function(){},ns=[],rs=ae("Reflect","construct"),ss=/^\s*(?:class|function)\b/,os=Qr(ss.exec),as=!ss.exec(is),cs=function(e){if(!$r(e))return !1;try{return rs(is,ns,e),!0;}catch(e){return !1;}},ds=function(e){if(!$r(e))return !1;switch(es(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return !1;}try{return as||!!os(ss,ts(e));}catch(e){return !0;}};ds.sham=!0;var ls=!rs||Zr(function(){var e;return cs(cs.call)||!cs(Object)||!cs(function(){e=!0;})||e;})?ds:cs,us=jr,hs=ls,ps=te,_s=ht("species"),Es=Array,ms=function(e){var t;return us(e)&&(t=e.constructor,(hs(t)&&(t===Es||us(t.prototype))||ps(t)&&null===(t=t[_s]))&&(t=void 0)),void 0===t?Es:t;},fs=function(e,t){return new(ms(e))(0===t?0:t);},gs=n,Ts=Ee,Ss=ht("species"),Rs=wi,Cs=n,Is=jr,vs=te,ys=Je,As=Bi,bs=function(e){if(e>9007199254740991)throw Gr("Maximum allowed index exceeded");return e;},ws=Yr,Os=fs,Ns=function(e){return Ts>=51||!gs(function(){var t=[];return (t.constructor={})[Ss]=function(){return {foo:1};},1!==t[e](Boolean).foo;});},Ds=Ee,Ps=ht("isConcatSpreadable"),Ls=Ds>=51||!Cs(function(){var e=[];return e[Ps]=!1,e.concat()[0]!==e;}),ks=function(e){if(!vs(e))return !1;var t=e[Ps];return void 0!==t?!!t:Is(e);};Rs({target:"Array",proto:!0,arity:1,forced:!Ls||!Ns("concat")},{concat:function(e){var t,i,n,r,s,o=ys(this),a=Os(o,0),c=0;for(t=-1,n=arguments.length;tr;)xs(n,i=t[r++])&&(~Fs(s,i)||js(s,i));return s;},Ws=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Hs=Gs,Ks=Ws,Ys=Object.keys||function(e){return Hs(e,Ks);},qs=N,zs=Zt,Js=Qt,Xs=ii,Qs=Z,Zs=Ys;Ms.f=qs&&!zs?Object.defineProperties:function(e,t){Xs(e);for(var i,n=Qs(t),r=Zs(t),s=r.length,o=0;s>o;)Js.f(e,i=r[o++],n[i]);return e;};var $s,eo=ae("document","documentElement"),to=nt,io=Ye("keys"),no=function(e){return io[e]||(io[e]=to(e));},ro=ii,so=Ms,oo=Ws,ao=Us,co=eo,lo=At,uo="prototype",ho="script",po=no("IE_PROTO"),_o=function(){},Eo=function(e){return "<"+ho+">"+e+"";},mo=function(e){e.write(Eo("")),e.close();var t=e.parentWindow.Object;return e=null,t;},fo=function(){try{$s=new ActiveXObject("htmlfile");}catch(e){}var e,t,i;fo="undefined"!=typeof document?document.domain&&$s?mo($s):(t=lo("iframe"),i="java"+ho+":",t.style.display="none",co.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(Eo("document.F=Object")),e.close(),e.F):mo($s);for(var n=oo.length;n--;)delete fo[uo][oo[n]];return fo();};ao[po]=!0;var go=Object.create||function(e,t){var i;return null!==e?(_o[uo]=ro(e),i=new _o(),_o[uo]=null,i[po]=e):i=fo(),void 0===t?i:so.f(i,t);},To={},So=Gs,Ro=Ws.concat("length","prototype");To.f=Object.getOwnPropertyNames||function(e){return So(e,Ro);};var Co={},Io=Ui,vo=Bi,yo=Yr,Ao=Array,bo=Math.max,wo=function(e,t,i){for(var n=vo(e),r=Io(t,n),s=Io(void 0===i?n:i,n),o=Ao(bo(s-r,0)),a=0;rg;g++)if((a||g in E)&&(p=m(h=E[g],g,_),e))if(t)S[g]=p;else if(p)switch(e){case 3:return !0;case 5:return h;case 6:return g;case 2:Na(S,h);}else switch(e){case 4:return !1;case 7:Na(S,h);}return s?-1:n||r?r:S;};},Pa={forEach:Da(0),map:Da(1),filter:Da(2),some:Da(3),every:Da(4),find:Da(5),findIndex:Da(6),filterReject:Da(7)},La=wi,ka=h,Ma=L,Ua=d,xa=N,Va=Te,Fa=n,Ba=Ze,ja=l,Ga=ii,Wa=Z,Ha=Ct,Ka=pn,Ya=B,qa=go,za=Ys,Ja=To,Xa=Co,Qa=ko,Za=O,$a=Qt,ec=Ms,tc=k,ic=Uo,nc=Vo,rc=Ye,sc=Us,oc=nt,ac=ht,cc=Fo,dc=zo,lc=$o,uc=ca,hc=va,pc=Pa.forEach,_c=no("hidden"),Ec="Symbol",mc="prototype",fc=hc.set,gc=hc.getterFor(Ec),Tc=Object[mc],Sc=ka.Symbol,Rc=Sc&&Sc[mc],Cc=ka.TypeError,Ic=ka.QObject,vc=Za.f,yc=$a.f,Ac=Xa.f,bc=tc.f,wc=Ua([].push),Oc=rc("symbols"),Nc=rc("op-symbols"),Dc=rc("wks"),Pc=!Ic||!Ic[mc]||!Ic[mc].findChild,Lc=xa&&Fa(function(){return 7!=qa(yc({},"a",{get:function(){return yc(this,"a",{value:7}).a;}})).a;})?function(e,t,i){var n=vc(Tc,t);n&&delete Tc[t],yc(e,t,i),n&&e!==Tc&&yc(Tc,t,n);}:yc,kc=function(e,t){var i=Oc[e]=qa(Rc);return fc(i,{type:Ec,tag:e,description:t}),xa||(i.description=t),i;},Mc=function(e,t,i){e===Tc&&Mc(Nc,t,i),Ga(e);var n=Ha(t);return Ga(i),Ba(Oc,n)?(i.enumerable?(Ba(e,_c)&&e[_c][n]&&(e[_c][n]=!1),i=qa(i,{enumerable:Ya(0,!1)})):(Ba(e,_c)||yc(e,_c,Ya(1,{})),e[_c][n]=!0),Lc(e,n,i)):yc(e,n,i);},Uc=function(e,t){Ga(e);var i=Wa(t),n=za(i).concat(Bc(i));return pc(n,function(t){xa&&!Ma(xc,i,t)||Mc(e,t,i[t]);}),e;},xc=function(e){var t=Ha(e),i=Ma(bc,this,t);return !(this===Tc&&Ba(Oc,t)&&!Ba(Nc,t))&&(!(i||!Ba(this,t)||!Ba(Oc,t)||Ba(this,_c)&&this[_c][t])||i);},Vc=function(e,t){var i=Wa(e),n=Ha(t);if(i!==Tc||!Ba(Oc,n)||Ba(Nc,n)){var r=vc(i,n);return !r||!Ba(Oc,n)||Ba(i,_c)&&i[_c][n]||(r.enumerable=!0),r;}},Fc=function(e){var t=Ac(Wa(e)),i=[];return pc(t,function(e){Ba(Oc,e)||Ba(sc,e)||wc(i,e);}),i;},Bc=function(e){var t=e===Tc,i=Ac(t?Nc:Wa(e)),n=[];return pc(i,function(e){!Ba(Oc,e)||t&&!Ba(Tc,e)||wc(n,Oc[e]);}),n;};Va||(Sc=function(){if(ja(Rc,this))throw Cc("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Ka(arguments[0]):void 0,t=oc(e),i=function(e){this===Tc&&Ma(i,Nc,e),Ba(this,_c)&&Ba(this[_c],t)&&(this[_c][t]=!1),Lc(this,t,Ya(1,e));};return xa&&Pc&&Lc(Tc,t,{configurable:!0,set:i}),kc(t,e);},ic(Rc=Sc[mc],"toString",function(){return gc(this).tag;}),ic(Sc,"withoutSetter",function(e){return kc(oc(e),e);}),tc.f=xc,$a.f=Mc,ec.f=Uc,Za.f=Vc,Ja.f=Xa.f=Fc,Qa.f=Bc,cc.f=function(e){return kc(ac(e),e);},xa&&nc(Rc,"description",{configurable:!0,get:function(){return gc(this).description;}})),La({global:!0,constructor:!0,wrap:!0,forced:!Va,sham:!Va},{Symbol:Sc}),pc(za(Dc),function(e){dc(e);}),La({target:Ec,stat:!0,forced:!Va},{useSetter:function(){Pc=!0;},useSimple:function(){Pc=!1;}}),La({target:"Object",stat:!0,forced:!Va,sham:!xa},{create:function(e,t){return void 0===t?qa(e):Uc(qa(e),t);},defineProperty:Mc,defineProperties:Uc,getOwnPropertyDescriptor:Vc}),La({target:"Object",stat:!0,forced:!Va},{getOwnPropertyNames:Fc}),lc(),uc(Sc,Ec),sc[_c]=!0;var jc=Te&&!!Symbol.for&&!!Symbol.keyFor,Gc=wi,Wc=ae,Hc=Ze,Kc=pn,Yc=Ye,qc=jc,zc=Yc("string-to-symbol-registry"),Jc=Yc("symbol-to-string-registry");Gc({target:"Symbol",stat:!0,forced:!qc},{for:function(e){var t=Kc(e);if(Hc(zc,t))return zc[t];var i=Wc("Symbol")(t);return zc[t]=i,Jc[i]=t,i;}});var Xc=wi,Qc=Ze,Zc=ye,$c=be,ed=jc,td=Ye("symbol-to-string-registry");Xc({target:"Symbol",stat:!0,forced:!ed},{keyFor:function(e){if(!Zc(e))throw TypeError($c(e)+" is not a symbol");if(Qc(td,e))return td[e];}});var id=d([].slice),nd=jr,rd=w,sd=R,od=pn,ad=d([].push),cd=wi,dd=ae,ld=f,ud=L,hd=d,pd=n,_d=w,Ed=ye,md=id,fd=function(e){if(rd(e))return e;if(nd(e)){for(var t=e.length,i=[],n=0;n=t.length?(e.target=void 0,Zl(void 0,!0)):Zl("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1);},"values"),Jl.Arguments=Jl.Array;var iu={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},nu=h,ru=ln,su=mi,ou=Gd,au=ht("toStringTag");for(var cu in iu){var du=nu[cu],lu=du&&du.prototype;lu&&ru(lu)!==au&&su(lu,au,cu),ou[cu]=ou.Array;}var uu=jd,hu=ht,pu=Qt.f,_u=hu("metadata"),Eu=Function.prototype;void 0===Eu[_u]&&pu(Eu,_u,{value:null}),zo("dispose"),zo("metadata");var mu=uu;zo("asyncDispose");var fu=d,gu=ae("Symbol"),Tu=gu.keyFor,Su=fu(gu.prototype.valueOf),Ru=gu.isRegisteredSymbol||function(e){try{return void 0!==Tu(Su(e));}catch(e){return !1;}};wi({target:"Symbol",stat:!0},{isRegisteredSymbol:Ru});for(var Cu=Ye,Iu=ae,vu=d,yu=ye,Au=ht,bu=Iu("Symbol"),wu=bu.isWellKnownSymbol,Ou=Iu("Object","getOwnPropertyNames"),Nu=vu(bu.prototype.valueOf),Du=Cu("wks"),Pu=0,Lu=Ou(bu),ku=Lu.length;Pu=a?e?"":void 0:(n=Wu(s,o))<55296||n>56319||o+1===a||(r=Wu(s,o+1))<56320||r>57343?e?Gu(s,o):n:e?Hu(s,o,o+2):r-56320+(n-55296<<10)+65536;};},Yu={codeAt:Ku(!1),charAt:Ku(!0)},qu=Yu.charAt,zu=pn,Ju=va,Xu=Yl,Qu=ql,Zu="String Iterator",$u=Ju.set,eh=Ju.getterFor(Zu);Xu(String,"String",function(e){$u(this,{type:Zu,string:zu(e),index:0});},function(){var e,t=eh(this),i=t.string,n=t.index;return n>=i.length?Qu(void 0,!0):(e=qu(i,n),t.index+=e.length,Qu(e,!1));});var th=i(Fo.f("iterator"));function ih(e){return ih="function"==typeof xu&&"symbol"==typeof th?function(e){return typeof e;}:function(e){return e&&"function"==typeof xu&&e.constructor===xu&&e!==xu.prototype?"symbol":typeof e;},ih(e);}var nh=i(Fo.f("toPrimitive"));function rh(e){var t=function(e,t){if("object"!==ih(e)||null===e)return e;var i=e[nh];if(void 0!==i){var n=i.call(e,t||"default");if("object"!==ih(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.");}return ("string"===t?String:Number)(e);}(e,"string");return "symbol"===ih(t)?t:String(t);}function sh(e,t,i){return (t=rh(t))in e?Fr(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e;}var oh=zi("Array").keys,ah=ln,ch=Ze,dh=l,lh=oh,uh=Array.prototype,hh={DOMTokenList:!0,NodeList:!0},ph=i(function(e){var t=e.keys;return e===uh||dh(uh,e)&&t===uh.keys||ch(hh,ah(e))?lh:t;}),_h=be,Eh=TypeError,mh=wo,fh=Math.floor,gh=function(e,t){var i=e.length,n=fh(i/2);return i<8?Th(e,t):Sh(e,gh(mh(e,0,n),t),gh(mh(e,n),t),t);},Th=function(e,t){for(var i,n,r=e.length,s=1;s0;)e[n]=e[--n];n!==s++&&(e[n]=i);}return e;},Sh=function(e,t,i,n){for(var r=t.length,s=i.length,o=0,a=0;o3)){if(Bh)return !0;if(Gh)return Gh<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2;}for(n=0;n<47;n++)Wh.push({k:t+n,v:i});}for(Wh.sort(function(e,t){return t.v-e.v;}),n=0;nMh(i)?1:-1;};}(e)),i=Lh(r),n=0;ns;s++)if((a=f(e[s]))&&Qp(n_,a))return a;return new i_(!1);}n=Zp(e,r);}for(c=h?e.next:n.next;!(d=Yp(c,n)).done;){try{a=f(d.value);}catch(e){e_(n,"throw",e);}if("object"==typeof a&&a&&Qp(n_,a))return a;}return new i_(!1);},s_=pn,o_=wi,a_=l,c_=nl,d_=Ol,l_=function(e,t,i){for(var n=cp(t),r=lp.f,s=dp.f,o=0;o2&&__(i,arguments[2]);var r=[];return m_(e,S_,{that:r}),h_(i,"errors",r),i;};d_?d_(R_,T_):l_(R_,T_,{name:!0});var C_=R_.prototype=u_(T_.prototype,{constructor:p_(1,R_),message:p_(1,""),name:p_(1,"AggregateError")});o_({global:!0,constructor:!0,arity:2},{AggregateError:R_});var I_,v_,y_,A_,b_="undefined"!=typeof process&&"process"==R(process),w_=ae,O_=Vo,N_=N,D_=ht("species"),P_=l,L_=TypeError,k_=function(e,t){if(P_(t,e))return e;throw L_("Incorrect invocation");},M_=ls,U_=be,x_=TypeError,V_=ii,F_=function(e){if(M_(e))return e;throw x_(U_(e)+" is not a constructor");},B_=Y,j_=ht("species"),G_=function(e,t){var i,n=V_(e).constructor;return void 0===n||B_(i=V_(n)[j_])?t:F_(i);},W_=TypeError,H_=function(e,t){if(e{};function lg(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:dg};return e.promise=new cg((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i);},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t));};}),e;}const ug=new Map(),hg=new Map(),pg=new Map();var _g,Eg;!function(e){e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot";}(_g||(_g={})),function(e){e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger";}(Eg||(Eg={}));var mg={exports:{}};!function(e,i){!function(t,n){var r="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",h="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",g="smarttv",T="wearable",S="embedded",R="Amazon",C="Apple",I="ASUS",v="BlackBerry",y="Browser",A="Chrome",b="Firefox",w="Google",O="Huawei",N="LG",D="Microsoft",P="Motorola",L="Opera",k="Samsung",M="Sharp",U="Sony",x="Xiaomi",V="Zebra",F="Facebook",B="Chromium OS",j="Mac OS",G=function(e){for(var t={},i=0;i0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):n:this[c[0]]=l?c[1].call(this,l,c[2]):n:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):n):this[c]=l||n;u+=2;}},q=function(e,t){for(var i in t)if(typeof t[i]===o&&t[i].length>0){for(var r=0;r2&&(e[d]="iPad",e[u]=f),e;},this.getEngine=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.engine),e;},this.getOS=function(){var e={};return e[l]=n,e[p]=n,Y.call(e,g,S.os),!e[l]&&T&&"Unknown"!=T.platform&&(e[l]=T.platform.replace(/chrome os/i,B).replace(/macos/i,j)),e;},this.getResult=function(){return {ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()};},this.getUA=function(){return g;},this.setUA=function(e){return g=typeof e===a&&e.length>350?K(e,350):e,this;},this.setUA(g),this;};X.VERSION="0.7.34",X.BROWSER=G([l,p,c]),X.CPU=G([_]),X.DEVICE=G([d,h,u,E,m,g,f,T,S]),X.ENGINE=X.OS=G([l,p]),e.exports&&(i=e.exports=X),i.UAParser=X;var Q=typeof t!==s&&(t.jQuery||t.Zepto);if(Q&&!Q.ua){var Z=new X();Q.ua=Z.getResult(),Q.ua.get=function(){return Z.getUA();},Q.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)Q.ua[i]=t[i];};}}("object"==typeof window?window:t);}(mg,mg.exports);const fg=new(i(mg.exports))();let gg=fg.getResult(),Tg=null;function Sg(e){if(!Tg){e&&fg.setUA(e),gg=fg.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return Eg.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return Eg.CHROME;case"Safari":case"Mobile Safari":return Eg.SAFARI;case"Edge":return Eg.EDGE;case"Firefox":return Eg.FIREFOX;case"QQBrowser":return Eg.QQ;case"Opera":return Eg.OPERA;case"WeChat":return Eg.WECHAT;default:return e.browser.name||"";}}(gg),i=function(e){let t;t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"";return t.split(".")[0];}(gg),n=function(e){if("Windows"===e.os.name)return e.os.version?e.os.name+" "+e.os.version:e.os.name;return e.os.name||"";}(gg),r=gg.os.version;if(!(t&&i&&n&&r))return {name:t,version:i,os:n,osVersion:r};Tg={name:t,version:i,os:n,osVersion:r};}return Tg;}function Rg(){return Sg().os;}function Cg(){const e=Sg();return "".concat(e.os," ").concat(e.osVersion);}function Ig(){const e=Sg();return !!("WebKit"===gg.engine.name&&e.os===_g.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Eg.SAFARI||Og()&&e.name!==Eg.SAFARI);}function vg(){const e=Sg();if(Ig()){if(e.os===_g.MAC_OS)return !0;if(e.os===_g.IOS){const e=gg.os.version&&gg.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return !0;if(e&&Number(e[0])>14)return !0;}}return !1;}function yg(){return "WebKit"===gg.engine.name;}function Ag(){return Sg().name===Eg.CHROME;}function bg(){return Sg().name===Eg.SAFARI;}function wg(){return Sg().name===Eg.FIREFOX;}function Og(){return Sg().os===_g.IOS;}function Ng(e){const t=Sg();return !(t.name!==Eg.CHROME||!t.osVersion)&&Number(t.version)>=e;}function Dg(e){const t=Sg();return !(t.name!==Eg.EDGE||!t.osVersion)&&Number(t.version)>=e;}function Pg(e){const t=Sg();return !(t.name!==Eg.OPERA||!t.osVersion)&&Number(t.version)>=e;}function Lg(){const e=Sg();return !(e.name!==Eg.CHROME||!e.osVersion)&&Number(e.version)<=90;}function kg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6;}function Mg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0]);}function Ug(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 16===Number(t[0]);}function xg(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1;}function Vg(){return bg()&&navigator.maxTouchPoints>0;}function Fg(){return Sg().name===Eg.WECHAT;}function Bg(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35;}function jg(){const e=Sg();if(e.name===Eg.EDGE||e.name===Eg.SAFARI)return !1;return !!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i);}function Gg(){return Rg()===_g.ANDROID;}function Wg(){const e=Sg();return Gg()&&(e.name===Eg.CHROME||e.name===Eg.WECHAT||/chrome|chromium/i.test(navigator.userAgent));}var Hg;!function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED";}(Hg||(Hg={}));let Kg=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),sh(this,"code",void 0),sh(this,"message",void 0),sh(this,"data",void 0),sh(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i;}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack);}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return "error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this;}throw(e){throw this.print("error",e),this;}};function Yg(e,t){if("boolean"!=typeof e)throw new Kg(Hg.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."));}function qg(e,t,i){if(bn(i).call(i,e))return;throw new Kg(Hg.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)));}function zg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(en||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return "number"==typeof e&&e%1==0;}(e)){throw new Kg(Hg.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"));}}function Jg(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact)){throw new Kg(Hg.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));}void 0!==e.min&&zg(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&zg(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&zg(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&zg(e.ideal,"".concat(t,".ideal"),1,1/0);}else zg(e,t,1,1/0);}function Xg(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Kg(Hg.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!$g(e,i,n,r))throw new Kg(Hg.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""));}function Qg(e,t){if(!Array.isArray(e))throw new Kg(Hg.INVALID_PARAMS,"".concat(t," should be an array"));}function Zg(e){return null==e;}function $g(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return "string"==typeof e&&e.length<=i&&e.length>=t&&(!n||function(e){if("string"!=typeof e)return !1;for(let t=0;t255)return !1;}return !0;}(e));}function eT(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),s=Number(!!i),o=Number(!i);return BigInt(n*o+r*s)<>BigInt(32)),s=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,s,n)):(e.setUint32(t,r,n),e.setUint32(t+4,s,n));}var iT,nT;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE";}(iT||(iT={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT";}(nT||(nT={}));const rT=new class{constructor(){sh(this,"_clientSize",null),sh(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),sh(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),sh(this,"getStyle",e=>window.getComputedStyle(e,null)),sh(this,"checkCssVisibleProperty",e=>{var t;let i=!0;const n=this.getStyle(e),{display:r,visibility:s,opacity:o,filter:a}=n;if(("none"===r||bn(t=["hidden","collapse"]).call(t,s)||Number(o)<.1)&&(i=!1),!i)return !1;if(a){a.split(" ").filter(e=>{var t;const i=e.split("(")[0];return bn(t=["brightness","blur","opacity"]).call(t,i);}).map(e=>{const[t,i]=e.split(/\(|\)/);return [t,Number(i.match(/^[0-9\.]+/))];}).forEach(e=>{const[t,n]=e;switch(t){case"brightness":(n<.1||n>3)&&(i=!1);break;case"blur":n>3&&(i=!1);break;case"opacity":n<.1&&(i=!1);}});}return i;}),sh(this,"checkPropertyUpToAllParentNodes",(e,t)=>{let i=!0,n=!0;const r=e=>t(e);let s=e;for(;s&&n;){r(s)||(i=!1,n=!1),s=s.parentElement,s||(n=!1);}return i;}),sh(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),sh(this,"getSizeAboutClient",e=>{const{width:t,height:i,left:n,right:r,top:s,bottom:o}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return {width:t,height:i,left:n,right:r,top:s,bottom:o,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)};}),sh(this,"checkActualSize",()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i);}),sh(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),sh(this,"checkCoverForAPoint",(e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i;}),sh(this,"getPointPositionList",()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,s=t/6,o=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(s*t*a-1e5)/a:s*t)*a)/a;o.push({x:c,y:d});}return [...o];}),sh(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),sh(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),sh(this,"checkSizeOfPartInClient",()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:s,clientMin:o}=this._clientSize;let a,c,d,l;if(e<0)a=0;else {if(!(e(this._clientSize=null,{visible:!1,reason:e})),sh(this,"checkOneElementVisible",e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(iT.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(iT.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(iT.SIZE);}}return this.returnHiddenResult(iT.STYLE);}return this.returnHiddenResult(nT.UNMOUNTED);}return this.returnHiddenResult(nT.INVALID_HTML_ELEMENT);}),sh(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement));}}();function sT(e){return new TextEncoder().encode(e);}const oT=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i;};const aT=async e=>{const t=function(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;efunction(e,t){let i="";return new Uint8Array(e).forEach(e=>{i+=e.toString(t).padStart(2,"0");}),i;}(await crypto.subtle.digest("SHA-256",sT(e)),16);class dT{constructor(){sh(this,"_events",{}),sh(this,"addListener",this.on);}getListeners(e){return this._events[e]?this._events[e].map(e=>e.listener):[];}on(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1});}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0});}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,1),0===this._events[e].length&&delete this._events[e];}removeAllListeners(e){e?delete this._events[e]:this._events={};}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map(e=>e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r1?t-1:0),n=1;n{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i);}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()));}});}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return -1;}}let lT=null;function uT(){if(lT)return lT;if(window.electron)return lT=window.electron;if(!window.require)return null;try{return lT=window.require("electron"),lT;}catch(e){return null;}}var hT,pT,_T,ET,mT,fT,gT,TT;function ST(e){return zg(e.timeout,"config.timeout",0,1e5),zg(e.timeoutFactor,"config.timeoutFactor",0,100,!1),zg(e.maxRetryCount,"config.maxRetryConfig",0,1/0),zg(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0;}function RT(e){if(!Array.isArray(e)||e.length<1)return !1;try{e.forEach(e=>{if(!e.urls)throw Error();});}catch(e){return !1;}return !0;}function CT(e){return Xg(e.turnServerURL,"turnServerURL"),Xg(e.username,"username"),Xg(e.password,"password"),e.udpport&&zg(e.udpport,"udpport",1,99999,!0),e.forceturn&&Yg(e.forceturn,"forceturn"),e.security&&Yg(e.security,"security"),e.tcpport&&zg(e.tcpport,"tcpport",1,99999,!0),!0;}function IT(e){return void 0!==e.level&&qg(e.level,"level",[1,2,3]),void 0!==e.delay&&zg(e.delay,"delay",0,3e3,!0),!0;}function vT(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r{e.emit(t,...n,i,r);});}function yT(e,t){if(0===e.getListeners(t).length)return cg.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r2?i-2:0),r=2;r2?r-2:0),o=2;o{i=e;},e=>{n=e;}),null!==n)throw n;if(null===i)throw new Kg(Hg.UNEXPECTED_ERROR,"handler is not sync");return i;}!function(e){e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.DATACHANNEL_FAILBACK="Client._datachannelFailback",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload";}(hT||(hT={})),function(e){e.TRACER="tracer";}(pT||(pT={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY";}(_T||(_T={})),function(e){e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.FALLBACK="FALLBACK",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE";}(ET||(ET={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.INJECT_STREAM_STATUS="stream-inject-status",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change";}(mT||(mT={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK";}(fT||(fT={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE";}(gT||(gT={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE";}(TT||(TT={}));const wT=new class extends dT{set networkState(e){this.emit(TT.NETWORK_STATE_CHANGE,e,this._networkState),e===gT.ONLINE?this.emit(TT.ONLINE):e===gT.OFFLINE&&(this.onlineWaiter=new cg(e=>{this.once(TT.ONLINE,()=>{this.onlineWaiter=void 0,e(gT.ONLINE);});}),this.emit(TT.OFFLINE)),this._networkState=e;}get networkState(){return this._networkState;}get isOnline(){return this._networkState===gT.ONLINE;}constructor(){super(),sh(this,"_moduleName","network-indicator"),sh(this,"_networkState",gT.ONLINE),sh(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=gT.ONLINE;}),window.addEventListener("offline",()=>{this.networkState=gT.OFFLINE;});}}();var OT=De,NT=Je,DT=K,PT=Bi,LT=TypeError,kT=function(e){return function(t,i,n,r){OT(i);var s=NT(t),o=DT(s),a=PT(s),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in o){r=o[c],c+=d;break;}if(c+=d,e?c<0:a<=c)throw LT("Reduce of empty array with no initial value");}for(;e?c>=0:a>c;c+=d)c in o&&(r=i(r,o[c],c,s));return r;};},MT={left:kT(!1),right:kT(!0)}.left;wi({target:"Array",proto:!0,forced:!b_&&Ee>79&&Ee<83||!Ih("reduce")},{reduce:function(e){var t=arguments.length;return MT(this,e,t,t>1?arguments[1]:void 0);}});var UT=zi("Array").reduce,xT=l,VT=UT,FT=Array.prototype,BT=i(function(e){var t=e.reduce;return e===FT||xT(FT,e)&&t===FT.reduce?VT:t;});function jT(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function GT(e){for(var t=1;t{-1===t.indexOf(e)&&t.push(e);}),t;}function KT(e){void 0!==cg?cg.resolve().then(e):setTimeout(e,0);}function YT(e){return JSON.parse(JSON.stringify(e));}function qT(e){try{return YT(e);}catch(t){return e;}}const zT={};function JT(e,t){zT[t]||(zT[t]=!0,e());}function XT(e){const t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;ee+t.length,0),r=new Uint8Array(new ArrayBuffer(n));let s=0;return t.forEach(e=>{r.set(e,s),s+=e.length;}),r;}function $T(e){return window.TextEncoder?new TextEncoder().encode(e).length:e.length;}function eS(e){let t=0;return /DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData),e.forEach(e=>{t+="string"==typeof e?$T(e):e.size;}),t+138;}function tS(e){const t=new Kg(Hg.TIMEOUT,"timeout");return new cg((i,n)=>{window.setTimeout(()=>n(t),e);});}function iS(e){return new cg(t=>{window.setTimeout(t,e);});}function nS(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+nS(e-i.length,"");}function rS(){return nS(32,"").toUpperCase();}const sS=()=>{};const oS=new class{constructor(){sh(this,"fnMap",new Map());}throttleByKey(e,t,i,n){for(var r=arguments.length,s=new Array(r>4?r-4:0),o=4;o{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t);},i);this.fnMap.set(t,{fn:e,threshold:i,timer:o,args:s,skipFn:n});}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,GT(GT({},r),{},{fn:e,args:s,skipFn:n}));}else {const r=window.setTimeout(()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t);},i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:s,skipFn:n});}}}(),aS=oS.throttleByKey.bind(oS);function cS(e){return "object"==typeof e&&null!==e&&!(e instanceof RegExp);}function dS(e,t){if(!cS(e)||!cS(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const i=[...e];for(let n=0;n0&&(i[n]=255&e,e>>=8,n++,!t||n!==t););return i;}let uS=1,hS=console;class pS{static setLogger(e){hS=e;}constructor(e){sh(this,"lockingPromise",cg.resolve()),sh(this,"locks",0),sh(this,"name",""),sh(this,"lockId",void 0),this.lockId=uS++,e&&(this.name=e),hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."));}get isLocked(){return this.locks>0;}lock(e){let t;this.locks+=1,hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new cg(i=>{t=()=>{this.locks-=1,hS.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i();};}),n=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>i),n;}}function _S(e,t){return function(i,n,r){const s=r.value;if("function"!=typeof s)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var o=arguments.length,a=new Array(o),c=0;c{await function(e){return new cg(t=>{window.setTimeout(t,e);});}(s),s*=r.timeoutFactor,s=Math.min(r.maxRetryTimeout,s);};let a=!1;const c=new cg(async(n,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;ca=!0,c;}let gS=class{constructor(e){sh(this,"input",[]),sh(this,"size",void 0),this.size=e;}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1);}mean(){var e;return 0===this.input.length?0:BT(e=this.input).call(e,(e,t)=>e+t)/this.input.length;}};function TS(e,t){return function(){return e.apply(t,arguments);};}const{toString:SS}=Object.prototype,{getPrototypeOf:RS}=Object,CS=(IS=Object.create(null),e=>{const t=SS.call(e);return IS[t]||(IS[t]=t.slice(8,-1).toLowerCase());});var IS;const vS=e=>(e=e.toLowerCase(),t=>CS(t)===e),yS=e=>t=>typeof t===e,{isArray:AS}=Array,bS=yS("undefined");const wS=vS("ArrayBuffer");const OS=yS("string"),NS=yS("function"),DS=yS("number"),PS=e=>null!==e&&"object"==typeof e,LS=e=>{if("object"!==CS(e))return !1;const t=RS(e);return !(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e);},kS=vS("Date"),MS=vS("File"),US=vS("Blob"),xS=vS("FileList"),VS=vS("URLSearchParams");function FS(e,t,{allOwnKeys:i=!1}={}){if(null==e)return;let n,r;if("object"!=typeof e&&(e=[e]),AS(e))for(n=0,r=e.length;n0;)if(n=i[r],t===n.toLowerCase())return n;return null;}const jS="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:commonjsGlobal,GS=e=>!bS(e)&&e!==jS;const WS=(HS="undefined"!=typeof Uint8Array&&RS(Uint8Array),e=>HS&&e instanceof HS);var HS;const KS=vS("HTMLFormElement"),YS=(({hasOwnProperty:e})=>(t,i)=>e.call(t,i))(Object.prototype),qS=vS("RegExp"),zS=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};FS(i,(i,r)=>{let s;!1!==(s=t(i,r,e))&&(n[r]=s||i);}),Object.defineProperties(e,n);},JS="abcdefghijklmnopqrstuvwxyz",XS="0123456789",QS={DIGIT:XS,ALPHA:JS,ALPHA_DIGIT:JS+JS.toUpperCase()+XS};const ZS=vS("AsyncFunction");var $S={isArray:AS,isArrayBuffer:wS,isBuffer:function(e){return null!==e&&!bS(e)&&null!==e.constructor&&!bS(e.constructor)&&NS(e.constructor.isBuffer)&&e.constructor.isBuffer(e);},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||NS(e.append)&&("formdata"===(t=CS(e))||"object"===t&&NS(e.toString)&&"[object FormData]"===e.toString()));},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&wS(e.buffer),t;},isString:OS,isNumber:DS,isBoolean:e=>!0===e||!1===e,isObject:PS,isPlainObject:LS,isUndefined:bS,isDate:kS,isFile:MS,isBlob:US,isRegExp:qS,isFunction:NS,isStream:e=>PS(e)&&NS(e.pipe),isURLSearchParams:VS,isTypedArray:WS,isFileList:xS,forEach:FS,merge:function e(){const{caseless:t}=GS(this)&&this||{},i={},n=(n,r)=>{const s=t&&BS(i,r)||r;LS(i[s])&&LS(n)?i[s]=e(i[s],n):LS(n)?i[s]=e({},n):AS(n)?i[s]=n.slice():i[s]=n;};for(let e=0,t=arguments.length;e(FS(t,(t,n)=>{i&&NS(t)?e[n]=TS(t,i):e[n]=t;},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),i&&Object.assign(e.prototype,i);},toFlatObject:(e,t,i,n)=>{let r,s,o;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-->0;)o=r[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==i&&RS(e);}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t;},kindOf:CS,kindOfTest:vS,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return -1!==n&&n===i;},toArray:e=>{if(!e)return null;if(AS(e))return e;let t=e.length;if(!DS(t))return null;const i=new Array(t);for(;t-->0;)i[t]=e[t];return i;},forEachEntry:(e,t)=>{const i=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1]);}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n;},isHTMLForm:KS,hasOwnProperty:YS,hasOwnProp:YS,reduceDescriptors:zS,freezeMethods:e=>{zS(e,(t,i)=>{if(NS(e)&&-1!==["arguments","caller","callee"].indexOf(i))return !1;const n=e[i];NS(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'");}));});},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach(e=>{i[e]=!0;});};return AS(e)?n(e):n(String(e).split(t)),i;},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,i){return t.toUpperCase()+i;}),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:BS,global:jS,isContextDefined:GS,ALPHABET:QS,generateString:(e=16,t=QS.ALPHA_DIGIT)=>{let i="";const{length:n}=t;for(;e--;)i+=t[Math.random()*n|0];return i;},isSpecCompliantForm:function(e){return !!(e&&NS(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator]);},toJSONObject:e=>{const t=new Array(10),i=(e,n)=>{if(PS(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const r=AS(e)?[]:{};return FS(e,(e,t)=>{const s=i(e,n+1);!bS(s)&&(r[t]=s);}),t[n]=void 0,r;}}return e;};return i(e,0);},isAsyncFn:ZS,isThenable:e=>e&&(PS(e)||NS(e))&&NS(e.then)&&NS(e.catch)};function eR(e,t,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r);}$S.inherits(eR,Error,{toJSON:function(){return {message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$S.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null};}});const tR=eR.prototype,iR={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{iR[e]={value:e};}),Object.defineProperties(eR,iR),Object.defineProperty(tR,"isAxiosError",{value:!0}),eR.from=(e,t,i,n,r,s)=>{const o=Object.create(tR);return $S.toFlatObject(e,o,function(e){return e!==Error.prototype;},e=>"isAxiosError"!==e),eR.call(o,e.message,t,i,n,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o;};function nR(e){return $S.isPlainObject(e)||$S.isArray(e);}function rR(e){return $S.endsWith(e,"[]")?e.slice(0,-2):e;}function sR(e,t,i){return e?e.concat(t).map(function(e,t){return e=rR(e),!i&&t?"["+e+"]":e;}).join(i?".":""):t;}const oR=$S.toFlatObject($S,{},null,function(e){return /^is[A-Z]/.test(e);});function aR(e,t,i){if(!$S.isObject(e))throw new TypeError("target must be an object");t=t||new FormData();const n=(i=$S.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return !$S.isUndefined(t[e]);})).metaTokens,r=i.visitor||d,s=i.dots,o=i.indexes,a=(i.Blob||"undefined"!=typeof Blob&&Blob)&&$S.isSpecCompliantForm(t);if(!$S.isFunction(r))throw new TypeError("visitor must be a function");function c(e){if(null===e)return "";if($S.isDate(e))return e.toISOString();if(!a&&$S.isBlob(e))throw new eR("Blob is not supported. Use a Buffer instead.");return $S.isArrayBuffer(e)||$S.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e;}function d(e,i,r){let a=e;if(e&&!r&&"object"==typeof e)if($S.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if($S.isArray(e)&&function(e){return $S.isArray(e)&&!e.some(nR);}(e)||($S.isFileList(e)||$S.endsWith(i,"[]"))&&(a=$S.toArray(e)))return i=rR(i),a.forEach(function(e,n){!$S.isUndefined(e)&&null!==e&&t.append(!0===o?sR([i],n,s):null===o?i:i+"[]",c(e));}),!1;return !!nR(e)||(t.append(sR(r,i,s),c(e)),!1);}const l=[],u=Object.assign(oR,{defaultVisitor:d,convertValue:c,isVisitable:nR});if(!$S.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!$S.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),$S.forEach(i,function(i,s){!0===(!($S.isUndefined(i)||null===i)&&r.call(t,i,$S.isString(s)?s.trim():s,n,u))&&e(i,n?n.concat(s):[s]);}),l.pop();}}(e),t;}function cR(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e];});}function dR(e,t){this._pairs=[],e&&aR(e,this,t);}const lR=dR.prototype;function uR(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]");}function hR(e,t,i){if(!t)return e;const n=i&&i.encode||uR,r=i&&i.serialize;let s;if(s=r?r(t,i):$S.isURLSearchParams(t)?t.toString():new dR(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s;}return e;}lR.append=function(e,t){this._pairs.push([e,t]);},lR.toString=function(e){const t=e?function(t){return e.call(this,t,cR);}:cR;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1]);},"").join("&");};var pR=class{constructor(){this.handlers=[];}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1;}eject(e){this.handlers[e]&&(this.handlers[e]=null);}clear(){this.handlers&&(this.handlers=[]);}forEach(e){$S.forEach(this.handlers,function(t){null!==t&&e(t);});}},_R={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ER={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:dR,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const mR="undefined"!=typeof window&&"undefined"!=typeof document,fR=(gR="undefined"!=typeof navigator&&navigator.product,mR&&["ReactNative","NativeScript","NS"].indexOf(gR)<0);var gR;const TR="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var SR={...Object.freeze({__proto__:null,hasBrowserEnv:mR,hasStandardBrowserEnv:fR,hasStandardBrowserWebWorkerEnv:TR}),...ER};function RR(e){function t(e,i,n,r){let s=e[r++];if("__proto__"===s)return !0;const o=Number.isFinite(+s),a=r>=e.length;if(s=!s&&$S.isArray(n)?n.length:s,a)return $S.hasOwnProp(n,s)?n[s]=[n[s],i]:n[s]=i,!o;n[s]&&$S.isObject(n[s])||(n[s]=[]);return t(e,i,n[s],r)&&$S.isArray(n[s])&&(n[s]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let s;for(n=0;n{t(function(e){return $S.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0]);}(e),n,i,0);}),i;}return null;}const CR={transitional:_R,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=$S.isObject(e);r&&$S.isHTMLForm(e)&&(e=new FormData(e));if($S.isFormData(e))return n?JSON.stringify(RR(e)):e;if($S.isArrayBuffer(e)||$S.isBuffer(e)||$S.isStream(e)||$S.isFile(e)||$S.isBlob(e))return e;if($S.isArrayBufferView(e))return e.buffer;if($S.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return aR(e,new SR.classes.URLSearchParams(),Object.assign({visitor:function(e,t,i,n){return SR.isNode&&$S.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments);}},t));}(e,this.formSerializer).toString();if((s=$S.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return aR(s?{"files[]":e}:e,t&&new t(),this.formSerializer);}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if($S.isString(e))try{return (t||JSON.parse)(e),$S.trim(e);}catch(e){if("SyntaxError"!==e.name)throw e;}return (i||JSON.stringify)(e);}(e)):e;}],transformResponse:[function(e){const t=this.transitional||CR.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&$S.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e);}catch(e){if(i){if("SyntaxError"===e.name)throw eR.from(e,eR.ERR_BAD_RESPONSE,this,null,this.response);throw e;}}}return e;}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:SR.classes.FormData,Blob:SR.classes.Blob},validateStatus:function(e){return e>=200&&e<300;},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$S.forEach(["delete","get","head","post","put","patch"],e=>{CR.headers[e]={};});var IR=CR;const vR=$S.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const yR=Symbol("internals");function AR(e){return e&&String(e).trim().toLowerCase();}function bR(e){return !1===e||null==e?e:$S.isArray(e)?e.map(bR):String(e);}function wR(e,t,i,n,r){return $S.isFunction(n)?n.call(this,t,i):(r&&(t=i),$S.isString(t)?$S.isString(n)?-1!==t.indexOf(n):$S.isRegExp(n)?n.test(t):void 0:void 0);}class OR{constructor(e){e&&this.set(e);}set(e,t,i){const n=this;function r(e,t,i){const r=AR(t);if(!r)throw new Error("header name must be a non-empty string");const s=$S.findKey(n,r);(!s||void 0===n[s]||!0===i||void 0===i&&!1!==n[s])&&(n[s||t]=bR(e));}const s=(e,t)=>$S.forEach(e,(e,i)=>r(e,i,t));return $S.isPlainObject(e)||e instanceof this.constructor?s(e,t):$S.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let i,n,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),i=e.substring(0,r).trim().toLowerCase(),n=e.substring(r+1).trim(),!i||t[i]&&vR[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n);}),t;})(e),t):null!=e&&r(t,e,i),this;}get(e,t){if(e=AR(e)){const i=$S.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t;}(e);if($S.isFunction(t))return t.call(this,e,i);if($S.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function");}}}has(e,t){if(e=AR(e)){const i=$S.findKey(this,e);return !(!i||void 0===this[i]||t&&!wR(0,this[i],i,t));}return !1;}delete(e,t){const i=this;let n=!1;function r(e){if(e=AR(e)){const r=$S.findKey(i,e);!r||t&&!wR(0,i[r],r,t)||(delete i[r],n=!0);}}return $S.isArray(e)?e.forEach(r):r(e),n;}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!wR(0,this[r],r,e,!0)||(delete this[r],n=!0);}return n;}normalize(e){const t=this,i={};return $S.forEach(this,(n,r)=>{const s=$S.findKey(i,r);if(s)return t[s]=bR(n),void delete t[r];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i);}(r):String(r).trim();o!==r&&delete t[r],t[o]=bR(n),i[o]=!0;}),this;}concat(...e){return this.constructor.concat(this,...e);}toJSON(e){const t=Object.create(null);return $S.forEach(this,(i,n)=>{null!=i&&!1!==i&&(t[n]=e&&$S.isArray(i)?i.join(", "):i);}),t;}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]();}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n");}get[Symbol.toStringTag](){return "AxiosHeaders";}static from(e){return e instanceof this?e:new this(e);}static concat(e,...t){const i=new this(e);return t.forEach(e=>i.set(e)),i;}static accessor(e){const t=(this[yR]=this[yR]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=AR(e);t[n]||(!function(e,t){const i=$S.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+i,{value:function(e,i,r){return this[n].call(this,t,e,i,r);},configurable:!0});});}(i,e),t[n]=!0);}return $S.isArray(e)?e.forEach(n):n(e),this;}}OR.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$S.reduceDescriptors(OR.prototype,({value:e},t)=>{let i=t[0].toUpperCase()+t.slice(1);return {get:()=>e,set(e){this[i]=e;}};}),$S.freezeMethods(OR);var NR=OR;function DR(e,t){const i=this||IR,n=t||i,r=NR.from(n.headers);let s=n.data;return $S.forEach(e,function(e){s=e.call(i,s,r.normalize(),t?t.status:void 0);}),r.normalize(),s;}function PR(e){return !(!e||!e.__CANCEL__);}function LR(e,t,i){eR.call(this,null==e?"canceled":e,eR.ERR_CANCELED,t,i),this.name="CanceledError";}$S.inherits(LR,eR,{__CANCEL__:!0});var kR=SR.hasStandardBrowserEnv?{write(e,t,i,n,r,s){const o=[e+"="+encodeURIComponent(t)];$S.isNumber(i)&&o.push("expires="+new Date(i).toGMTString()),$S.isString(n)&&o.push("path="+n),$S.isString(r)&&o.push("domain="+r),!0===s&&o.push("secure"),document.cookie=o.join("; ");},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null;},remove(e){this.write(e,"",Date.now()-864e5);}}:{write(){},read:()=>null,remove(){}};function MR(e,t){return e&&!function(e){return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(e);}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e;}(e,t):t;}var UR=SR.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function n(i){let n=i;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname};}return i=n(window.location.href),function(e){const t=$S.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host;};}():function(){return !0;};function xR(e,t){let i=0;const n=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];r||(r=c),i[s]=a,n[s]=c;let l=o,u=0;for(;l!==s;)u+=i[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-i,c=n(a);i=s;const d={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r};d[t?"download":"upload"]=!0,e(d);};}var VR="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,i){let n=e.data;const r=NR.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s);}if($S.isFormData(n))if(SR.hasStandardBrowserEnv||SR.hasStandardBrowserWebWorkerEnv)r.setContentType(!1);else if(!1!==(o=r.getContentType())){const[e,...t]=o?o.split(";").map(e=>e.trim()).filter(Boolean):[];r.setContentType([e||"multipart/form-data",...t].join("; "));}let l=new XMLHttpRequest();if(e.auth){const t=e.auth.username||"",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";r.set("Authorization","Basic "+btoa(t+":"+i));}const u=MR(e.baseURL,e.url);function h(){if(!l)return;const n=NR.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new eR("Request failed with status code "+i.status,[eR.ERR_BAD_REQUEST,eR.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i);}(function(e){t(e),d();},function(e){i(e),d();},{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null;}if(l.open(e.method.toUpperCase(),hR(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=h:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(h);},l.onabort=function(){l&&(i(new eR("Request aborted",eR.ECONNABORTED,e,l)),l=null);},l.onerror=function(){i(new eR("Network Error",eR.ERR_NETWORK,e,l)),l=null;},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||_R;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new eR(t,n.clarifyTimeoutError?eR.ETIMEDOUT:eR.ECONNABORTED,e,l)),l=null;},SR.hasStandardBrowserEnv&&(c&&$S.isFunction(c)&&(c=c(e)),c||!1!==c&&UR(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&kR.read(e.xsrfCookieName);t&&r.set(e.xsrfHeaderName,t);}void 0===n&&r.setContentType(null),"setRequestHeader"in l&&$S.forEach(r.toJSON(),function(e,t){l.setRequestHeader(t,e);}),$S.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",xR(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",xR(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(i(!t||t.type?new LR(null,e,l):t),l.abort(),l=null);},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const p=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||"";}(u);p&&-1===SR.protocols.indexOf(p)?i(new eR("Unsupported protocol "+p+":",eR.ERR_BAD_REQUEST,e)):l.send(n||null);});};const FR={http:null,xhr:VR};$S.forEach(FR,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t});}catch(e){}Object.defineProperty(e,"adapterName",{value:t});}});const BR=e=>`- ${e}`,jR=e=>$S.isFunction(e)||null===e||!1===e;var GR={getAdapter:e=>{e=$S.isArray(e)?e:[e];const{length:t}=e;let i,n;const r={};for(let s=0;s`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new eR("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(BR).join("\n"):" "+BR(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT");}return n;},adapters:FR};function WR(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new LR(null,e);}function HR(e){WR(e),e.headers=NR.from(e.headers),e.data=DR.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return GR.getAdapter(e.adapter||IR.adapter)(e).then(function(t){return WR(e),t.data=DR.call(e,e.transformResponse,t),t.headers=NR.from(t.headers),t;},function(t){return PR(t)||(WR(e),t&&t.response&&(t.response.data=DR.call(e,e.transformResponse,t.response),t.response.headers=NR.from(t.response.headers))),Promise.reject(t);});}const KR=e=>e instanceof NR?e.toJSON():e;function YR(e,t){t=t||{};const i={};function n(e,t,i){return $S.isPlainObject(e)&&$S.isPlainObject(t)?$S.merge.call({caseless:i},e,t):$S.isPlainObject(t)?$S.merge({},t):$S.isArray(t)?t.slice():t;}function r(e,t,i){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e,i):n(e,t,i);}function s(e,t){if(!$S.isUndefined(t))return n(void 0,t);}function o(e,t){return $S.isUndefined(t)?$S.isUndefined(e)?void 0:n(void 0,e):n(void 0,t);}function a(i,r,s){return s in t?n(i,r):s in e?n(void 0,i):void 0;}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t)=>r(KR(e),KR(t),!0)};return $S.forEach(Object.keys(Object.assign({},e,t)),function(n){const s=c[n]||r,o=s(e[n],t[n],n);$S.isUndefined(o)&&s!==a||(i[n]=o);}),i;}const qR="1.6.7",zR={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{zR[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e;};});const JR={};zR.transitional=function(e,t,i){function n(e,t){return "[Axios v"+qR+"] Transitional option '"+e+"'"+t+(i?". "+i:"");}return (i,r,s)=>{if(!1===e)throw new eR(n(r," has been removed"+(t?" in "+t:"")),eR.ERR_DEPRECATED);return t&&!JR[r]&&(JR[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s);};};var XR={assertOptions:function(e,t,i){if("object"!=typeof e)throw new eR("options must be an object",eR.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-->0;){const s=n[r],o=t[s];if(o){const t=e[s],i=void 0===t||o(t,s,e);if(!0!==i)throw new eR("option "+s+" must be "+i,eR.ERR_BAD_OPTION_VALUE);}else if(!0!==i)throw new eR("Unknown option "+s,eR.ERR_BAD_OPTION);}},validators:zR};const QR=XR.validators;let ZR=class{constructor(e){this.defaults=e,this.interceptors={request:new pR(),response:new pR()};}async request(e,t){try{return await this._request(e,t);}catch(e){if(e instanceof Error){let t;Error.captureStackTrace?Error.captureStackTrace(t={}):t=new Error();const i=t.stack?t.stack.replace(/^.+\n/,""):"";e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i;}throw e;}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=YR(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&XR.assertOptions(i,{silentJSONParsing:QR.transitional(QR.boolean),forcedJSONParsing:QR.transitional(QR.boolean),clarifyTimeoutError:QR.transitional(QR.boolean)},!1),null!=n&&($S.isFunction(n)?t.paramsSerializer={serialize:n}:XR.assertOptions(n,{encode:QR.function,serialize:QR.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&$S.merge(r.common,r[t.method]);r&&$S.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e];}),t.headers=NR.concat(s,r);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected));});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected);});let l,u=0;if(!a){const e=[HR.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u{if(!i._listeners)return;let t=i._listeners.length;for(;t-->0;)i._listeners[t](e);i._listeners=null;}),this.promise.then=e=>{let t;const n=new Promise(e=>{i.subscribe(e),t=e;}).then(e);return n.cancel=function(){i.unsubscribe(t);},n;},e(function(e,n,r){i.reason||(i.reason=new LR(e,n,r),t(i.reason));});}throwIfRequested(){if(this.reason)throw this.reason;}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e];}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1);}static source(){let e;return {token:new eC(function(t){e=t;}),cancel:e};}}var tC=eC;const iC={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(iC).forEach(([e,t])=>{iC[t]=e;});var nC=iC;const rC=function e(t){const i=new $R(t),n=TS($R.prototype.request,i);return $S.extend(n,$R.prototype,i,{allOwnKeys:!0}),$S.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(YR(t,i));},n;}(IR);rC.Axios=$R,rC.CanceledError=LR,rC.CancelToken=tC,rC.isCancel=PR,rC.VERSION=qR,rC.toFormData=aR,rC.AxiosError=eR,rC.Cancel=rC.CanceledError,rC.all=function(e){return Promise.all(e);},rC.spread=function(e){return function(t){return e.apply(null,t);};},rC.isAxiosError=function(e){return $S.isObject(e)&&!0===e.isAxiosError;},rC.mergeConfig=YR,rC.AxiosHeaders=NR,rC.formToJSON=e=>RR($S.isHTMLForm(e)?new FormData(e):e),rC.getAdapter=GR.getAdapter,rC.HttpStatusCode=nC,rC.default=rC;var sC=rC;function oC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function aC(e){for(var t=1;t{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),dC+=$T(t.data)):i&&(t.data.size?dC+=t.data.size:t.data instanceof FormData?dC+=eS(t.data):dC+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,sC.request(t).then(e=>{"string"==typeof e.data?lC+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?lC+=e.data.byteLength:lC+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data);}).catch(e=>{sC.isCancel(e)?s(new Kg(Hg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new Kg(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new Kg(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new Kg(Hg.NETWORK_ERROR,e.message));});});}async function hC(e,t){const i=new Blob([t.data],{type:"buffer"});return await uC(e,aC(aC({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0);}const pC=()=>"HTTPS"===(cC||cC||(cC=(window.location.protocol.split(":")[0]||"").toUpperCase(),cC)),_C=()=>void 0!==window.isSecureContext;const EC=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return "".concat(e,".").concat(i);}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return "".concat(e,".").concat(100*(Number(t)+1));}return "4.0.0.999";}("4.20.2"),mC=function(){try{return !0===JSON.parse("true");}catch(e){return !0;}}();var fC;!function(e){e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn";}(fC||(fC={}));const gC="v4.20.2-0-g8ae7fdad(3/20/2024, 4:48:46 PM)",TC={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:100,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],PLUGIN_INFO:[]};function SC(e,t,i){var n,r;bn(n=Object.keys(TC)).call(n,e)&&(!i&&bn(r=Object.keys(CC)).call(r,e)||(TC[e]=t,"ENABLE_VIDEO_SEI"===e&&!0===t&&(TC.ENABLE_ENCODED_TRANSFORM=!0)));}function RC(e){return TC[e];}const CC={};function IC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function vC(e){for(var t=1;te.trackId===t.metric.trackId);return -1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})});}case yC.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex(e=>e.userId===t.metric.userId&&e.type===t.metric.type);return -1!==n?(i[n]=vC(vC({},i[n]),t.metric),vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...i]})})):vC(vC({},e),{},{keyMetrics:vC(vC({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})});}case yC.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case yC.RECORD_JOIN_CHANNEL_SERVICE:return "number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=vC(vC({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case yC.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case yC.SET_USE_DATACHANNEL:return vC(vC({},e),{},{useDataChannel:t.val});case yC.SET_USE_P2P:return vC(vC({},e),{},{useP2P:t.val});case yC.SET_TRANSPORT_TYPE:return vC(vC({},e),{},{p2pTransport:t.val});default:return e;}}(this.state,e);}set sessionId(e){this.dispatch({type:yC.SET_SESSION_ID,sessionId:e});}get sessionId(){return this.state.sessionId;}set codec(e){this.state.codec=e;}get codec(){return this.state.codec;}get mode(){return this.state.mode;}get audioCodec(){return this.state.audioCodec;}get clientId(){return this.state.clientId;}set p2pId(e){this.dispatch({type:yC.SET_P2P_ID,p2pId:e});}get p2pId(){return this.state.p2pId;}set dcId(e){this.dispatch({type:yC.SET_DC_ID,dcId:e});}get dcId(){return this.state.dcId;}set uid(e){this.dispatch({type:yC.SET_UID,uid:e});}get uid(){return this.state.uid;}set intUid(e){this.dispatch({type:yC.SET_INT_UID,intUid:e});}get intUid(){return this.state.intUid;}set pubId(e){this.dispatch({type:yC.SET_PUB_ID,pubId:e});}get pubId(){return this.state.pubId;}set cloudProxyServerMode(e){this.dispatch({type:yC.SET_CLOUD_PROXY_SERVER_MODE,mode:e});}get cloudProxyServerMode(){return this.state.cloudProxyServerMode;}set useDataChannel(e){this.dispatch({type:yC.SET_USE_DATACHANNEL,val:e});}get useDataChannel(){return this.state.useDataChannel;}set useP2P(e){this.dispatch({type:yC.SET_USE_P2P,val:e});}get useP2P(){return this.state.useP2P;}set p2pTransport(e){this.dispatch({type:yC.SET_TRANSPORT_TYPE,val:e});}get p2pTransport(){return this.state.p2pTransport;}clientCreated(){this.dispatch({type:yC.KEY_METRIC_CLIENT_CREATED,metric:Date.now()});}joinStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_START,metric:Date.now()});}joinEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_END,metric:Date.now()});}requestAPStart(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_START,metric:Date.now()});}requestAPEnd(){this.dispatch({type:yC.KEY_METRIC_REQUEST_AP_END,metric:Date.now()});}joinGatewayStart(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()});}joinGatewayEnd(){this.dispatch({type:yC.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()});}peerConnectionStart(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()});}peerConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()});}descriptionStart(){this.dispatch({type:yC.KEY_METRIC_DESCRIPTION_START,metric:Date.now()});}signalChannelOpen(){this.dispatch({type:yC.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()});}iceConnectionEnd(){this.dispatch({type:yC.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()});}publish(e,t,i,n){this.dispatch({type:yC.KEY_METRIC_PUBLISH,metric:vC(vC({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})});}subscribe(e,t,i,n,r,s,o){this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC(vC(vC({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),s&&{streamAdded:s}),o&&{firstDecoded:o})});}massSubscribe(e,t,i,n){e.forEach(e=>{this.dispatch({type:yC.KEY_METRIC_SUBSCRIBE,metric:vC(vC(vC({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})});});}get keyMetrics(){return this.state.keyMetrics;}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map(e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return "number"!=typeof t?(this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:vC(vC({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:yC.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t);}catch(e){return 0;}}resetJoinChannelServiceRecords(){this.dispatch({type:yC.RESET_JOIN_CHANNEL_SERVICE_RECORDS});}resetKeyMetrics(){this.dispatch({type:yC.RESET_KEY_METRICS});}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords;}catch(e){return [];}}get avoidJoinStart(){return this.state.avoidJoinStart;}set avoidJoinStart(e){this.dispatch({type:yC.AVOID_JOIN_START,avoidJoinStart:e});}}var bC,wC;!function(e){e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1";}(bC||(bC={})),function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722";}(wC||(wC={}));const OC=128,NC=96,DC=1e3,PC=10;let LC=0;const kC=new class extends dT{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e);}}();class MC{constructor(e){sh(this,"logger",void 0),sh(this,"prefixLists",[]),this.logger=e;}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{for(const t in VC)if(Object.prototype.hasOwnProperty.call(VC,t)&&VC[t]===e)return t;return "DEFAULT";};const jC=new class{constructor(){sh(this,"proxyServerURL",void 0),sh(this,"logLevel",VC.DEBUG),sh(this,"uploadState","collecting"),sh(this,"uploadLogWaitingList",[]),sh(this,"uploadLogUploadingList",[]),sh(this,"uploadErrorCount",0),sh(this,"currentLogID",0),sh(this,"url",void 0),sh(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t);});}debug(){for(var e=arguments.length,t=new Array(e),i=0;i{this.log(...t);},Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=UC()+" Agora-SDK [".concat(BC(n),"]:"),this.appendLogToWaitingList(n,...t),n{this.uploadLog(...t);},Date.now()-FC);const n=Math.max(0,Math.min(4,t[0]));t[0]=UC()+" Agora-SDK [".concat(BC(n),"]:"),this.appendLogToWaitingList(n,...t);}appendLogToWaitingList(e){if(!RC("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ");}),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval();}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval();}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:EC,process_id:RC("PROCESS_ID"),payload:JSON.stringify(e)};return fS(async()=>{const e=await sC.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(RC("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(RC("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t;}},()=>(this.uploadLogUploadingList=[],!1),e=>(e.response?kC.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?kC.reportLogUploadError({status:e.request.status,message:e.message}):kC.reportLogUploadError({status:-1,message:e.message}),!0),{timeout:RC("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:RC("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")});}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,RC("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_INTERVAL"));}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),RC("UPLOAD_LOG_RETRY_INTERVAL_V1"));}));}}();var GC,WC;function HC(e){return Xg(e.reportId,"params.reportId",0,100,!1),Xg(e.category,"params.category",0,100,!1),Xg(e.event,"params.event",0,100,!1),Xg(e.label,"params.label",0,100,!1),zg(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0;}!function(e){e.FREE="free",e.UPLOADING="uploading";}(GC||(GC={})),function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API";}(WC||(WC={}));const KC={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var YC,qC,zC,JC;function XC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function QC(e){for(var t=1;t{for(const t of e){const e=QC(QC({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:pT.TRACER});this.sendApiInvoke(e);}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),RC("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),RC("EVENT_REPORT_SEND_INTERVAL"));}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e);}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void jC.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,jC.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"ms")),this.baseInfoMap.set(e,t);}setAppId(e){this._appId=e;}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,s=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),o=!!RC("SHOW_REPORT_INVOKER_LOG");o&&jC.info("".concat(t.name," start"),t.options);let a=!1;iS(t.timeout).then(()=>{a||(this.sendApiInvoke(QC(QC({},s()),{},{error:Hg.API_INVOKE_TIMEOUT,success:!1})),jC.debug("".concat(t.name," timeout")));});const c=new Kg(Hg.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return {onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!0},t.reportResult&&{result:e})),o&&jC.info("".concat(t.name," onSuccess")),e;};return i?aS(n,t.name+"Success",i,()=>a=!0):n();},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(QC(QC({},s()),{},{success:!1,error:e})),o&&jC.info("".concat(t.name," onFailure"),e.toString());};return i?aS(n,t.name+"Error",i,()=>a=!0):n();}};}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:RC("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:mC?"global":"oversea",areas:RC("AREAS")&&RC("AREAS").join(",")},t.extend),{stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,u=Date.now(),h=QC(QC({},n),{},{eventType:YC.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:gC,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:t.mode,process:RC("PROCESS_ID"),appType:RC("APP_TYPE"),success:!0,version:EC,stringUid:s,channelProfile:o,channelMode:a,isABTestSuccess:c,lsid:d,clientType:20,clientRole:l,serviceId:RC("PROCESS_ID"),extensionID:RC("PLUGIN_INFO").join(",")||""});this.send({type:qC.SESSION,data:h},!0);}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3});this.send({type:qC.JOIN_CHOOSE_SERVER,data:s},!0);}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:qC.REQ_USER_ACCOUNT,data:s},!0);}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:s,avoidJoinStartTime:o,isProxy:a,addr:c}=t,d=r-(s&&o?o:i.startTime),l=QC(QC({},n),{},{eventType:YC.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:s,signalChannel:t.signalChannel}),u=l.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),s)this.send({type:qC.JOIN_GATEWAY,data:l},!0);else {let e;if(c){if(a){const t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:a?1:0};}else {const t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/(:|p=)[0-9]{1,6}/g);e={isSuccess:u,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(/:|p=/g)[1]:"",isProxy:a?1:0};}}else e={isSuccess:u,gatewayIp:"",port:"",isProxy:a?1:0};delete l.success,delete l.eventType,delete l.firstSuccess,l.vid=Number(l.vid);const t=Object.assign({},l,e,{eventType:YC.REJOIN_GATEWAY});this.send({type:qC.RE_JOIN_GATEWAY,data:t},!0);}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=QC(QC({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:qC.JOIN_CHANNEL_TIMEOUT,data:r},!0);}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:qC.PUBLISH,data:s},!0);}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,s=Date.now(),o=QC(QC({},r),{},{eventType:YC.SUBSCRIBE,lts:s,eventElapse:t.eventElapse,elapse:s-n.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?o.peerSuid=t.peerid:o.peer=t.peerid,this.send({type:qC.SUBSCRIBE,data:o},!0);}wsCompressorInit(e){var t;const i=[...ph(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC({},s),{},{eventType:YC.WS_COMPRESSOR_INIT,lts:o,eventElapse:e.eventElapse,elapse:o-r.startTime,status:e.status?1:2});this.send({type:qC.WS_COMPRESSOR_INIT,data:a},!0);}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o,firstDecodeFrame:Math.max(o-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0);}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{elapse:o-r.startTime,eventType:t,lts:o});this.send({type:i,data:a},!0);}pcStats(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),elapse:r-i.startTime,eventType:YC.PC_STATS,lts:r});this.send({type:qC.PC_STATS,data:s},!0);}updateRemoteRTPCapabilities(e,t){if(e){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{vid:void 0===n.vid?0:Number(n.vid),eventType:YC.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:qC.UPDATE_REMOTE_RTPCAPABILITIES,data:s},!0);}}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const s=r.info,o=Date.now(),a=QC(QC(QC({},s),n),{},{eventType:t,lts:o});this.send({type:i,data:a},!0);}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:qC.STREAM_SWITCH,data:s},!0);}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_APPCENTER,data:s},!0);}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{eventType:YC.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:qC.REQUEST_PROXY_WORKER_MANAGER,data:s},!0);}setProxyServer(e){this.proxyServer=e,e?jC.debug("reportProxyServerurl: ".concat(e)):jC.debug("disable reportProxyServerurl: ".concat(e));}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC({},n),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:qC.PEER_PUBLISH_STATUS,data:s},!0);}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return [e];e[t]="";const r=$T(JSON.stringify(e));let s=0;const o=[];let a=0;for(let c=0;cthis.send({type:qC.WORKER_EVENT,data:e},!0));}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.AP_WORKER_EVENT,data:s},!0);}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:qC.JOIN_WEB_PROXY_AP,data:s},!0);}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),s=QC(QC(QC({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:qC.WEBSOCKET_QUIT,data:s},!0);}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>RC("CUSTOM_REPORT_LIMIT"))throw new Kg(Hg.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0;},5e3));const i=Date.now(),n=t.map(t=>({type:qC.USER_ANALYTICS,data:QC(QC({sid:e},t),{},{lts:i})}));try{RC("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n);}catch(e){throw jC.error("send custom report message failed",e.toString()),new Kg(Hg.CUSTOM_REPORT_SEND_FAILED,e.message);}}sendApiInvoke(e){const t=RC("NOT_REPORT_EVENT");if(e.tag&&bn(t)&&bn(t).call(t,e.tag))return !1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:s}=i.info;let o;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Kg){const{code:t,message:i}=e.error;o=t||i||e.error.toString();}else o=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?o:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:qC.API_INVOKE,data:a},!1),!0;}appendSessionId(){ZC.__CLIENT_LIST__.forEach(e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;iRC("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1);}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1);}sendItems(e,t){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t);}e.push(...n);for(const e of [...i]){var r;if(-1!==this.ltsList.indexOf(e.data.lts))e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts);else this.ltsList.push(e.data.lts),ep(r=this.ltsList).call(r,(e,t)=>e-t);}t||(this.lastSendNormalEventTime=Date.now());return RC("ENABLE_EVENT_REPORT")?(i.length&&(RC("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{RC("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>RC("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-RC("NORMAL_EVENT_QUEUE_CAPACITY")),jC.warning("report: drop normal events"))));})(i)),e):e;}async postDataToStatsCollector2(e){wT.networkState===gT.OFFLINE&&(await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]));const t=e=>{let t=new Uint8Array();return e.forEach(e=>{const i=sT(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(qC).forEach(i=>{let[n,r]=i;r===e.type&&(t=EventNameToID[n]);}),t;})(e),s=new DataView(n);s.setUint16(0,i.byteLength,!0),s.setUint8(2,255&r),s.setUint8(3,r>>>8&255),s.setUint8(4,r>>>16&255),t=oT(t,new Uint8Array(n)),t=oT(t,i);}),t;},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(RC("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(RC("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await uC(n,{timeout:1e4,data:t(e),headers:QC(QC({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0);}catch(e){if(1===r)throw e;continue;}return;}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(e=>JSON.stringify(e)),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0;})(e[0])};wT.networkState===gT.OFFLINE&&(await cg.race([wT.onlineWaiter,iS(2*ES.maxRetryTimeout)]));const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("EVENT_REPORT_DOMAIN"),"&p=").concat(RC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(RC("EVENT_REPORT_DOMAIN"),":").concat(RC("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(RC("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(RC("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(RC("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(RC("STATS_COLLECTOR_PORT")).concat(n)));try{t?await hC(r,{timeout:1e4,data:i}):await uC(r,{timeout:1e4,data:i});}catch(t){if(1===e)throw t;continue;}return;}}createBaseInfo(e,t){const i=Object.assign({},KC);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i;}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:pT.TRACER}).onSuccess();}}function $C(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const s=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),o=0;o(c.onSuccess(e.reportResult&&t),t)).catch(e=>{throw c.onError(e),e;}):(c.onSuccess(e.reportResult&&t),t);}catch(e){throw c.onError(e),e;}};}return n;};}sh(ZC,"__CLIENT_LIST__",[]);const eI=new ZC();kC.on("REPORT_LOG_UPLOAD",e=>{e.networkState=wT.networkState,eI.reportApiInvoke(null,{name:"logUploadError",options:e,tag:pT.TRACER});});const tI=["CHINA","GLOBAL"],iI=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const s=r.join(""),o={};return o[e]=n,o[t]=s,Object.assign(o,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1});}();window.DEFAULT_TURN_CONFIG=iI,mC||(TC.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],TC.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],TC.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],TC.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],TC.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],TC.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],TC.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",TC.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",TC.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",TC.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",TC.AREAS=["NORTH_AMERICA","OVERSEA"]);const nI=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],rI=[];function sI(e,t){return !!t&&rI.some(i=>i.uid===e&&i.channelName===t);}ZC.__CLIENT_LIST__=rI;var oI,aI,cI,dI,lI,uI,hI,pI,_I,EI,mI,fI,gI,TI,SI,RI,CI,II=zi("Array").values,vI=ln,yI=Ze,AI=l,bI=II,wI=Array.prototype,OI={DOMTokenList:!0,NodeList:!0},NI=i(function(e){var t=e.values;return e===wI||AI(wI,e)&&t===wI.values||yI(OI,vI(e))?bI:t;});function DI(e,t,i,n){var r,s=arguments.length,o=s<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,i,o):r(t,i))||o);return s>3&&o&&Object.defineProperty(t,i,o),o;}function PI(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t);}!function(e){e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY";}(oI||(oI={})),function(e){e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver";}(aI||(aI={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR";}(cI||(cI={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR";}(dI||(dI={})),function(e){e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND";}(lI||(lI={})),function(e){e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV";}(uI||(uI={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY";}(hI||(hI={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed";}(pI||(pI={})),function(e){e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream";}(_I||(_I={})),function(e){e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag";}(EI||(EI={})),function(e){e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats";}(mI||(mI={})),function(e){e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list";}(fI||(fI={})),function(e){e.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",e.NEED_ANSWER="NEED_ANSWER",e.NEED_RENEGOTIATE="NEED_RENEGOTIATE",e.P2P_LOST="P2P_LOST",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NEED_UNPUB="NEED_UNPUB",e.NEED_UNSUB="NEED_UNSUB",e.NEED_UPLOAD="NEED_UPLOAD",e.NEED_CONTROL="NEED_CONTROL",e.START_RECONNECT="START_RECONNECT",e.END_RECONNECT="END_RECONNECT",e.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT";}(gI||(gI={})),function(e){e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY";}(TI||(TI={})),function(e){e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire";}(SI||(SI={}));class LI extends Kg{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),sh(this,"name","AgoraRTCException");}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,jC);}throw(){super.throw(jC);}}function kI(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw jC.error("Invalid Channel Name ".concat(e)),new LI(Hg.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,");}function MI(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||$g(e,1,255)))throw new LI(Hg.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&jC.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.");}!function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming";}(RI||(RI={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",e[e.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",e[e.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN";}(CI||(CI={}));const UI={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},xI={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function VI(e,t){Xg(e.url,"".concat(t,".url"),1,1e3,!1),Zg(e.x)||zg(e.x,"".concat(t,".x"),0,1e4),Zg(e.y)||zg(e.y,"".concat(t,".y"),0,1e4),Zg(e.width)||zg(e.width,"".concat(t,".width"),0,1e4),Zg(e.height)||zg(e.height,"".concat(t,".height"),0,1e4),Zg(e.zOrder)||zg(e.zOrder,"".concat(t,".zOrder"),0,255),Zg(e.alpha)||zg(e.alpha,"".concat(t,".alpha"),0,1,!1);}const FI={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},BI={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var jI,GI,WI,HI,KI,YI,qI,zI,JI,XI,QI,ZI,$I,ev;function tv(e){if(!e.channelName)throw new LI(Hg.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new LI(Hg.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Xg(e.token,"info.token",1,2047),MI(e.uid),kI(e.channelName),!0;}!function(e){e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.INJECT_STREAM_STATUS="@live_uap-inject-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address";}(jI||(jI={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager";}(GI||(GI={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN";}(WI||(WI={})),function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort";}(HI||(HI={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile";}(KI||(KI={})),function(e){e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE";}(YI||(YI={})),function(e){e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE";}(qI||(qI={})),function(e){e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED";}(zI||(zI={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low";}(JI||(JI={})),function(e){e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_FAILBACK="datachannel_failback",e.RESET_SIGNAL="reset-signal";}(XI||(XI={})),function(e){e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON";}(QI||(QI={})),function(e){e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7";}(ZI||(ZI={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel";}($I||($I={})),function(e){e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS";}(ev||(ev={}));const iv=[ev.AFRICA,ev.ASIA,ev.CHINA,ev.EUROPE,ev.GLOBAL,ev.INDIA,ev.JAPAN,ev.NORTH_AMERICA,ev.OCEANIA,ev.OVERSEA,ev.SOUTH_AMERICA];var nv;!function(e){e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL";}(nv||(nv={}));const rv={CHINA:{},ASIA:{CODE:nv.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:nv.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:nv.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:nv.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:nv.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:nv.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:nv.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:nv.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:nv.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:nv.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:nv.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:nv.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:nv.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};var sv,ov,av,cv,dv,lv,uv,hv,pv,_v,Ev,mv,fv,gv,Tv,Sv,Rv,Cv,Iv,vv,yv,Av,bv,wv;mC&&(rv.CHINA={CODE:nv.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]}),function(e){e.UPDATE_BITRATE_LIMIT="update_bitrate_limit";}(sv||(sv={}));class Ov extends dT{constructor(e,t){super(),sh(this,"onICEConnectionStateChange",void 0),sh(this,"onConnectionStateChange",void 0),sh(this,"onDTLSTransportStateChange",void 0),sh(this,"onDTLSTransportError",void 0),sh(this,"onICETransportStateChange",void 0),sh(this,"onFirstAudioReceived",void 0),sh(this,"onFirstVideoReceived",void 0),sh(this,"onFirstAudioDecoded",void 0),sh(this,"onFirstVideoDecoded",void 0),sh(this,"onFirstVideoDecodedTimeout",void 0),sh(this,"onSelectedLocalCandidateChanged",void 0),sh(this,"onSelectedRemoteCandidateChanged",void 0);}}class Nv extends Ov{constructor(e,t){super(e,t);}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive";}(ov||(ov={})),function(e){e.VIDEO="video",e.AUDIO="audio";}(av||(av={})),function(e){e[e.UDP=0]="UDP",e[e.TCP=1]="TCP",e[e.RELAY=2]="RELAY";}(cv||(cv={})),function(e){e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.TCP_RESTART=1]="TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED";}(dv||(dv={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack";}(lv||(lv={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected";}(uv||(uv={})),function(e){e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE";}(hv||(hv={})),function(e){e.MUTE_LOCAL_VIDEO="mute_local_video",e.MUTE_LOCAL_AUDIO="mute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.MUTE_REMOTE_VIDEO="mute_remote_video",e.MUTE_REMOTE_AUDIO="mute_remote_audio",e.UNMUTE_REMOTE_VIDEO="unmute_remote_video",e.UNMUTE_REMOTE_AUDIO="unmute_remote_audio";}(pv||(pv={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED";}(_v||(_v={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED";}(Ev||(Ev={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url";}(mv||(mv={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK";}(fv||(fv={})),function(e){e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback";}(gv||(gv={})),function(e){e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation";}(Tv||(Tv={})),function(e){e[e.APP_TYPE_INVALID_VALUE=-1]="APP_TYPE_INVALID_VALUE",e[e.APP_TYPE_NATIVE=0]="APP_TYPE_NATIVE",e[e.APP_TYPE_NATIVE_COCOS=1]="APP_TYPE_NATIVE_COCOS",e[e.APP_TYPE_NATIVE_UNITY=2]="APP_TYPE_NATIVE_UNITY",e[e.APP_TYPE_NATIVE_ELECTRON=3]="APP_TYPE_NATIVE_ELECTRON",e[e.APP_TYPE_NATIVE_FLUTTER=4]="APP_TYPE_NATIVE_FLUTTER",e[e.APP_TYPE_NATIVE_UNREAL=5]="APP_TYPE_NATIVE_UNREAL",e[e.APP_TYPE_NATIVE_XAMARIN=6]="APP_TYPE_NATIVE_XAMARIN",e[e.APP_TYPE_NATIVE_API_CLOUD=7]="APP_TYPE_NATIVE_API_CLOUD",e[e.APP_TYPE_NATIVE_REACT_NATIVE=8]="APP_TYPE_NATIVE_REACT_NATIVE",e[e.APP_TYPE_NATIVE_PYTHON=9]="APP_TYPE_NATIVE_PYTHON",e[e.APP_TYPE_NATIVE_COCOS_CREATOR=10]="APP_TYPE_NATIVE_COCOS_CREATOR",e[e.APP_TYPE_NATIVE_RUST=11]="APP_TYPE_NATIVE_RUST",e[e.APP_TYPE_NATIVE_C_SHARP=12]="APP_TYPE_NATIVE_C_SHARP",e[e.APP_TYPE_NATIVE_CEF=13]="APP_TYPE_NATIVE_CEF",e[e.APP_TYPE_NATIVE_UNI_APP=14]="APP_TYPE_NATIVE_UNI_APP",e[e.APP_TYPE_WEBRTC=1e3]="APP_TYPE_WEBRTC",e[e.APP_TYPE_WEBRTC_REACT=1001]="APP_TYPE_WEBRTC_REACT",e[e.APP_TYPE_WEBRTC_VUE=1002]="APP_TYPE_WEBRTC_VUE",e[e.APP_TYPE_WEBRTC_ANGULAR=1003]="APP_TYPE_WEBRTC_ANGULAR";}(Sv||(Sv={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED";}(Rv||(Rv={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url";}(Cv||(Cv={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED";}(Iv||(Iv={})),function(e){e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check";}(vv||(vv={})),function(e){e.ABORT="abort";}(yv||(yv={})),function(e){e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video";}(Av||(Av={})),function(e){e[e.SUCCESS=1]="SUCCESS",e[e.FAILED=0]="FAILED";}(bv||(bv={})),function(e){e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed";}(wv||(wv={}));const Dv={[cI.ACCESS_POINT]:{[uI.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[uI.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[uI.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[uI.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[uI.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[uI.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[uI.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[cI.UNILBS]:{[lI.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[lI.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[lI.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[lI.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[lI.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[lI.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[lI.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[lI.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[lI.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[lI.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[lI.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[lI.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[cI.STRING_UID_ALLOCATOR]:{[dI.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[dI.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[dI.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function Pv(e){const t=Dv[Math.floor(e/1e4)];if(!t)return {desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===cI.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return {desc:e.toString(),retry:!1};if("2"===t.toString()[0])return {desc:e.toString(),retry:!0};}return {desc:"unkonw error",retry:!1};}return i;}const Lv={[hI.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[hI.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[hI.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[hI.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[hI.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[hI.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[hI.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[hI.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[hI.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[hI.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[hI.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[hI.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[hI.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[hI.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[hI.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[hI.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[hI.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[hI.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[hI.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[hI.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[hI.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[hI.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[hI.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[hI.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[hI.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[hI.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[hI.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[hI.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[hI.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[hI.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[hI.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[hI.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[hI.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[hI.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[hI.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[hI.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[hI.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[hI.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[hI.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[hI.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[hI.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[hI.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[hI.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[hI.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[hI.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[hI.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[hI.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[hI.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[hI.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[hI.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[hI.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[hI.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[hI.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[hI.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[hI.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[hI.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[hI.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[hI.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[hI.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[hI.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[hI.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[hI.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function kv(e){const t=Lv[e];return t||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"};}function Mv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Uv(e){for(var t=1;te.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING);}function Vv(e,t){if("string"==typeof e)return e;const{proxy:i,host:n,port:r}=e;if(t){const e=RC("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(e,"/ws/?p=").concat(Number(r)+150);}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r);}const Fv=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,Bv=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,jv=/wss:\/\/(.+):([0-9]+)\/?/,Gv=/wss:\/\/(.[^\/]+)\/?/;let Wv=0;class Hv{constructor(e,t){sh(this,"id",0),sh(this,"store",void 0),sh(this,"recordIndex",void 0),sh(this,"websockets",[]),sh(this,"try443PortDuration",2e3),sh(this,"forceCloseWSDuration",5e3),sh(this,"try443PortTimeout",null),sh(this,"forceCloseTimeout",null),sh(this,"isTry443PortFailed",!1),sh(this,"isNormalPortFailed",!1),sh(this,"useDoubleDomain",!1),sh(this,"useProxy",!1),sh(this,"startTime",Date.now()),this.id=++Wv,this.try443PortDuration=RC("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t;}closeAllWebsockets(){this.websockets.forEach(e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close();}),this.websockets.length=0;}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout);}logger(){var e;const t=Date.now()-this.startTime;for(var i=arguments.length,n=new Array(i),r=0;r{var i;return bn(i=e.host).call(i,t);});o||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)n.forEach(i=>{a.push(Vv(Uv(Uv({},e),{},{host:e.host.replace(o,i)}),t));});else {const i=Uv({},e);if(t&&o){const e=n.find(e=>e!==o);e&&(i.host=i.host.replace(o,e));}a.push(Vv(i,t));}try{a.forEach(e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",s.push(t),this.logger("ws is connecting:",t.url);});}catch(n){if(this.logger("ws create failed"),s.forEach(e=>e.close()),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new LI(Hg.WS_ERR,"init websocket failed! Error: ".concat(n.toString()));}const c=lg();this.store&&this.store.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},this.recordIndex),s.forEach(e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach(t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)));}),this.websockets.length=0,c.resolve(e);},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState)),t?this.isTry443PortFailed=xv(s):this.isNormalPortFailed=xv(s),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(t&&this.isTry443PortFailed||!t&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:QI.A_ROUND_WS_FAILED}));},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data));}),this.websockets.push(...s);return i||(()=>{const i=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.websockets.forEach(e=>e.readyState!==WebSocket.OPEN&&e.close());};if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{if(this.logger("2s timeout, isWebsocket created: ",c.isResolved),c.isResolved)return i();Sg().os===_g.MAC_OS&&wg()&&i(),this.createWebSocket(e,!0,!0).then(e=>c.resolve(e)).catch(e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed");}),this.forceCloseTimeout=window.setTimeout(i,this.forceCloseWSDuration);},this.try443PortDuration);})(),c.promise;}chooseBestWebsocket(e,t,i,n){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,i,n;return [,t,i,n]=e.match(Fv)||[],t||([,i,n]=e.match(Bv)||[]),i&&n||([,i,n]=e.match(jv)||[]),i&&n||([,i]=e.match(Gv)||[]),i||jC.warning("un-destructible url: ",e),{proxy:t,host:i,port:n||"443"};}(e)),this.recordIndex=n,this.useProxy=!!e.proxy,i&&this.useProxy&&(jC.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally(()=>this.clearTimeout());}}function Kv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}class Yv extends dT{get url(){return this.websocket&&this.websocket.url||null;}get reconnectMode(){return this._reconnectMode;}set reconnectMode(e){var t;bn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e;}get state(){return this._state;}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(SI.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(SI.CONNECTED):"closed"===this._state?this.emit(SI.CLOSED):"failed"===this._state&&this.emit(SI.FAILED));}resetReconnectCount(e){jC.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0;}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),sh(this,"connectionID",0),sh(this,"currentURLIndex",0),sh(this,"urls",[]),sh(this,"_reconnectMode","tryNext"),sh(this,"reconnectReason",void 0),sh(this,"_initMutex",new pS("websocket")),sh(this,"name",void 0),sh(this,"_state","closed"),sh(this,"reconnectInterrupter",void 0),sh(this,"websocket",void 0),sh(this,"retryConfig",void 0),sh(this,"reconnectCount",0),sh(this,"forceCloseTimeout",5e3),sh(this,"onlineReconnectListener",void 0),sh(this,"useCompress",void 0),sh(this,"tryDoubleDomain",!1),sh(this,"use443PortOnly",!1),sh(this,"wsInflateLength",0),sh(this,"wsDeflateLength",0),sh(this,"closeEstablishingWs",()=>{}),sh(this,"store",void 0),sh(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=e,this.retryConfig=function(e){for(var t=1;t{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gT.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=a));});}getConnection(){return this.websocket||void 0;}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=await this._initMutex.lock();this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{const e=lg(),t=this.urls[this.currentURLIndex];this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(SI.CLOSED,()=>{e.reject(new Kg(Hg.WS_DISCONNECT));}),this.once(SI.CONNECTED,e.resolve),await e.promise;}catch(e){}finally{i();}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout(()=>e.close(),500):e.close(),this.websocket=void 0;}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs();}reconnect(e,t){if(!this.websocket)return void jC.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),jC.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t});}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Kg(Hg.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e);}catch(e){throw new Kg(Hg.WS_ERR,"send websocket message error"+e.toString());}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength;}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t};}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0;}async createWebSocketConnection(e){var t;const i=lg();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const n=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),jC.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve();},r=async e=>{var t;if(jC.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new Kg(Hg.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else {"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const t=AT(this,SI.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,n=await this.reconnectWithAction(t);if("closed"===this.state)return void jC.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return i.reject(new Kg(Hg.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);i.resolve();}},s=e=>{this.emit(SI.ON_MESSAGE,e);},o=e=>{jC.warn("[".concat(this.connectionID,"] ws open error ").concat(e));};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),RC("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=RC("GATEWAY_WSS_ADDRESS")),jC.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=s,this.websocket.onerror=o,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a;}catch(e){const t="closed"===this.state,n=e instanceof Kg,s=n&&e.code===Hg.WS_ABORT,o=n&&e.code===Hg.WS_ERR,c=n?e.message:e&&(e.reason||e.toString());jC.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:s?"aborted":"error",errors:[e]},a),t||o?(i.reject(t?new Kg(Hg.WS_DISCONNECT,"websocket is closed: ".concat(c)):new Kg(Hg.WS_ERR,"init websocket failed: ".concat(c))),o&&jC.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e);}return i.promise;}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return !1;if(0===this.urls.length)return !1;if("closed"===this.state)return !1;jC.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||wT.isOnline||!wT.onlineWaiter||(this.onlineReconnectListener=wT.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0;}));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){const t=mS(this.reconnectCount,this.retryConfig);jC.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await cg.race([iS(t),this.onlineReconnectListener||new cg(()=>{})]);}if("closed"===this._state||!i)return !1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(SI.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e);};try{if("retry"===e)this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);jC.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(SI.RECONNECT_WAITTING_FINISH,e),await n(this.urls[this.currentURLIndex],e);}else "recover"===e&&(jC.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(SI.RECONNECT_WAITTING_FINISH,e),this.urls=await vT(this,SI.REQUEST_NEW_URLS),this.currentURLIndex=0,await n(this.urls[this.currentURLIndex],e));}catch(i){var r;jC.error("[".concat(this.name,"] reconnect failed ").concat(i&&i.toString()));const n=null==i||null===(r=i.data)||void 0===r?void 0:r.desc;return Array.isArray(n)&&bn(n).call(n,"dynamic key expired")?(this.emit(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,t);}return !0;}}class qv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0);}async chooseBestWebsocketConnection(e,t){const i=lg(),n=function(e,t){return new Hv(e,t);}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{jC.debug("[choose-best-ws] close establishing websockets"),n.closeAllWebsockets(),i.reject(new Kg(Hg.WS_ABORT,"choose best websocket aborted"));};const r=RC("GATEWAY_DOMAINS");return jC.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),n.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally(()=>{this.closeEstablishingWs=void 0;});}}class zv extends Yv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0);}async chooseBestWebsocketConnection(e,t){return new cg((i,n)=>{let r=!1;const s=[];this.closeEstablishingWs=()=>{jC.debug("[choose-best-ws] close establishing websockets"),s.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close();}),n(new Kg(Hg.WS_ABORT,"choose best websocket aborted"));};const o=RC("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=o.find(t=>-1!==c?bn(e).call(e,t,c):bn(e).call(e,t));jC.debug("[choose-best-ws] currentDomain: ",d,", domains: ",o);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{o.forEach(t=>{const i=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),n=new WebSocket(i);n.binaryType="arraybuffer",s.push(n),jC.debug("[choose-best-ws] ws is connecting:",n.url);});}catch(e){for(jC.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(e=>e.close());s.length;)s.pop();l=!0;}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},t),s.forEach(e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;jC.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter(t=>t!==e).forEach(e=>{jC.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close();}),r=!0,i(e);},e.onclose=e=>{if(a=e,r)return;s.find(e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))||(jC.debug("[choose-best-ws] all websocket is closed"),r=!0,n(a));},e.onmessage=t=>{jC.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data));};}),iS(this.forceCloseTimeout).then(()=>{s.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close();});});}if(l){var h;let r;jC.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),s.push(r),r.binaryType="arraybuffer";}catch(e){const t=new Kg(Hg.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return jC.error("[".concat(this.name,"]").concat(t)),void n(t);}r.onopen=()=>{i(r);},r.onclose=e=>{n(e);},r.onmessage=e=>{jC.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data));},iS(this.forceCloseTimeout).then(()=>{r&&r.readyState!==WebSocket.OPEN&&r.close();});}}).then(e=>(this.closeEstablishingWs=void 0,e)).catch(e=>{throw this.closeEstablishingWs=void 0,e;});}}class Jv extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket&&this.websocket.url||null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"wsInflateDataTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close();}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fT.OFFLINE);});}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t();},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.PUBLISH_DATASTREAM&&e!==EI.SUBSCRIBE&&e!==EI.SUBSCRIBE_DATASTREAM&&e!==EI.UNSUBSCRIBE&&e!==EI.UNSUBSCRIBE_DATASTREAM&&e!==EI.UNPUBLISH&&e!==EI.UNPUBLISH_DATASTREAM&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,()=>{i(new LI(Hg.DISCONNECT_P2P));}),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,()=>{i(new LI(Hg.DISCONNECT_P2P));});});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),this.websocket.sendMessage(s,!0),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((t,i)=>{this.once(_I.WS_CONNECTED,()=>t(this.joinResponse)),this.once(_I.WS_CLOSED,()=>i(this.initError||new LI(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData();},2e4);});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents());}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,QI.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return !!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id});}),!0);}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e});}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(SI.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(SI.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(SI.WILL_RECONNECT,(e,t,i)=>{const n=bT(this,_I.IS_P2P_DISCONNECTED),r=n||"retry"!==e;n&&"retry"===e&&(jC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=QI.P2P_DISCONNECTED),r&&(jC.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(_I.REPORT_JOIN_GATEWAY,t||QI.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),i(e);}),this.websocket.on(SI.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{jC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",fT.SERVER_ERROR);}):this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code||QI.UNKNOWN_REASON,this.url||""),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fT.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);});}}var Xv="\t\n\v\f\r                 \u2028\u2029\ufeff",Qv=J,Zv=pn,$v=Xv,ey=d("".replace),ty=RegExp("^["+$v+"]+"),iy=RegExp("(^|[^"+$v+"])["+$v+"]+$"),ny=function(e){return function(t){var i=Zv(Qv(t));return 1&e&&(i=ey(i,ty,"")),2&e&&(i=ey(i,iy,"$1")),i;};},ry={start:ny(1),end:ny(2),trim:ny(3)},sy=zd.PROPER,oy=n,ay=Xv,cy=ry.trim;wi({target:"String",proto:!0,forced:function(e){return oy(function(){return !!ay[e]()||"​…᠎"!=="​…᠎"[e]()||sy&&ay[e].name!==e;});}("trim")},{trim:function(){return cy(this);}});var dy,ly,uy=zi("String").trim,hy=l,py=uy,_y=String.prototype,Ey=i(function(e){var t=e.trim;return "string"==typeof e||e===_y||hy(_y,e)&&t===_y.trim?py:t;});function my(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function fy(e){for(var t=1;t{let{ip:t,port:i}=e;return {address:"".concat(t,":").concat(i)};});const i=RC("GATEWAY_DOMAINS");let n=i[1]&&bn(t).call(t,i[1])?1:0;return e.map(e=>{let{domain_prefix:t,port:r,ip:s}=e;if(t)return {address:"".concat(t,".").concat(i[n++%i.length],":").concat(r)};const o=/^[\.\:\d]+$/.test(s),a=o?"".concat(s.replace(/[^\d]/g,"-"),".").concat(i[n++%i.length],":").concat(r):"".concat(s,":").concat(r);return o||jC.info("Unidentified as ip: ".concat(s,", use as host")),{ip:s,port:r,address:a};});}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){const e=n.split(";");for(let t=0;t=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0;}function Iy(e,t){let i,n,r;switch(t){case dy.CHOOSE_SERVER:n=4096,r="choose server";break;case dy.CLOUD_PROXY:n=1048576,r="proxy";break;case dy.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case dy.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new LI(Hg.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1});}if(e.response_body.forEach(t=>{t.buffer&&t.buffer.flag===n&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map(e=>fy(fy({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:fy(fy({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert});}),!i)throw new LI(Hg.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i;}async function vy(e,t){return await cg.all(e.addresses.map(async e=>({address:gy(e.ip),tcpport:e.port,udpport:e.port,username:t&&RC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():iI.username,password:t&&RC("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await cT(t.toString()):iI.password})));}function yy(e,t){const i=t._videoHeight||t.getMediaStreamTrack(!0).getSettings().height;return i?Math.max(i/Sy(e.height),1):(jC.warning("can't get ori-track's height, default scale down 4 times for low stream"),4);}function Ay(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:s,protocol:o}=e;return "local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:o}:{candidateType:t,relayProtocol:i,address:r,port:s,protocol:o};}function by(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}!function(e){e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK";}(dy||(dy={}));class wy extends dT{get url(){return this._url?this._url:null;}get reconnectMode(){return this._reconnectMode;}set reconnectMode(e){var t;bn(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e;}get state(){return this._state;}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(gv.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(gv.CONNECTED):"closed"===this._state?this.emit(gv.CLOSED):"failed"===this._state&&this.emit(gv.FAILED));}constructor(e,t,i,n){super(),sh(this,"connectionID",0),sh(this,"currentURLIndex",0),sh(this,"reconnectReason",void 0),sh(this,"_reconnectMode","tryNext"),sh(this,"_name",void 0),sh(this,"_state","closed"),sh(this,"_retryConfig",void 0),sh(this,"_reconnectCount",0),sh(this,"_forceCloseTimeout",5e3),sh(this,"_onlineReconnectListener",void 0),sh(this,"_closeEstablishingTransmitter",()=>{}),sh(this,"_store",void 0),sh(this,"_joinChannelServiceRecordIndex",void 0),sh(this,"_useCompress",void 0),sh(this,"_inflateLength",0),sh(this,"_deflateLength",0),this._store=n,this._name=e,this._retryConfig=function(e){for(var t=1;te.close(),500):e.close(),this._transmitter=void 0;}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter();}reconnect(e,t){if(!this._transmitter)return void jC.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),jC.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t});}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t};}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength;}clearInflateData(){this._inflateLength=0,this._deflateLength=0;}}!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack";}(ly||(ly={}));class Oy{constructor(e,t,i){sh(this,"version",1),sh(this,"initialRTO",void 0),sh(this,"maxBatchAckCount",void 0),sh(this,"maxRTO",void 0),sh(this,"initialRTT",void 0),sh(this,"ID",void 0),sh(this,"rtt",void 0),sh(this,"packetNumber",1),sh(this,"rtoRatioMap",new Map()),sh(this,"timeoutMap",new Map()),sh(this,"unorderedPacketQueue",[]),sh(this,"batchAckPacketQueue",[]),sh(this,"lastOrderedPacketNumber",0),sh(this,"batchAckTimer",void 0),sh(this,"sendImpl",void 0),sh(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=nS(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:RC("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:RC("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:RC("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:RC("TRANSMITTER_MAX_RTO");}packetize(e,t){return {type:ly.Default,version:this.version,packetNumber:t,payload:e};}serialize(e){switch(e.type){case ly.Default:{let t;if("string"==typeof e.payload){t=new TextEncoder().encode(e.payload);}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),tT(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i;}case ly.Ack:{const t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),tT(i,8,BigInt(e.ackSendTs)),t;}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case ly.Default:{const r=t.getUint32(3),s=eT(t,7),o=e.slice(15),a=new TextDecoder().decode(o);return {version:i,type:n,packetNumber:r,sendTs:Number(s),payload:a};}case ly.Ack:{const e=t.getUint32(3),r=t.getUint8(7),s=eT(t,8);return {version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(s)};}default:throw jC.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n));}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout(()=>{this.resendMessage(t);},i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t);}onData(e){const t=this.deserialize(e);t.type===ly.Default?this.ack(t):t.type===ly.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t));}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(e=>{let[t,i]=e;window.clearTimeout(i);}),this.timeoutMap=new Map(),this.rtoRatioMap=new Map(),this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer);}resendMessage(e){const t=this.calculateRTO(e),i=window.setTimeout(()=>{this.resendMessage(e);},t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e);}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i;}}updateRTT(e,t){const i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8;}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout(()=>{this.batchAck();},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break;}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1;}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t);}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:ly.Ack,version:this.version};this.sendPacket(t);}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:ly.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[];}sendPacket(e){e.type===ly.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t);}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t);}}}class Ny extends wy{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),sh(this,"_initMutex",void 0),sh(this,"_reconnectInterrupter",void 0),sh(this,"_url",void 0),sh(this,"_transmitter",void 0),sh(this,"_addresses",void 0),sh(this,"_reliableTransmission",void 0),this._initMutex=new pS("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*n)/10);gT.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s),wT.on(TT.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===gT.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n));});}getConnection(){if(this._reliableTransmission)return this._reliableTransmission;}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex(e=>e.fingerprint||RC("FINGERPRINT"));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(gv.CLOSED,()=>i(new LI(Hg.WS_DISCONNECT))),this.once(gv.CONNECTED,()=>t());};return this._initMutex.lock().then(e=>new cg((e,t)=>{i(e,t);}).then(()=>{e();}).catch(()=>{e();}));}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new LI(Hg.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e);}catch(e){throw new LI(Hg.WS_ERR,"send datachannel signal message error"+e.toString());}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null);}sendMessageWithJSON(e){const t=JSON.stringify(e);return {compressed:t,compressedLength:t.length,origin:e};}sendMessageWithUint8Array(e){return {compressed:e,compressedLength:e.byteLength,origin:e};}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new cg((t,i)=>{var n;const r=()=>{jC.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t();},s=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),jC.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data);};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),jC.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();vT(this,gv.TO_CONNECT_DATACHANNEL,e).then(e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;jC.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new Oy(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e));},e=>{"string"==typeof e&&this.emit(gv.ON_MESSAGE,e);}),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d();},r&&r(),n.onclose=s,n.onmessage=o,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a;}).catch(e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof LI&&e.code===Hg.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof LI&&e.code===Hg.WS_ERR){const t=new LI(Hg.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return jC.error("[".concat(this._name,"]").concat(t)),void i(t);}s&&s(e);}else i(new LI(Hg.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())));});});}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return !1;if(!this._addresses)return !1;if("closed"===this.state)return !1;this._onlineReconnectListener||wT.networkState!==gT.OFFLINE||(this._onlineReconnectListener=wT.onlineWaiter&&wT.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0;}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1;},t){const t=mS(this._reconnectCount,this._retryConfig);jC.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await cg.race([iS(t),this._onlineReconnectListener||new cg(()=>{})]);}if("closed"===this.state||!i)return !1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(gv.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e);};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e);}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e=this._addresses.length)return jC.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);jC.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(gv.RECONNECT_WAITTING_FINISH,e),await n(t,e);}else "recover"===e&&(jC.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(gv.RECONNECT_WAITTING_FINISH,e),this.emit(gv.FAILBACK));return !0;}catch(i){var r,s;return jC.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&bn(s=i.data.desc).call(s,"dynamic key expired")?(this.emit(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t);}}}class Dy extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket?this.websocket.url:null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"inflateDataTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"onWebsocketMessage",e=>{if(e instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")&&(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Ny("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fv.OFFLINE);});}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((t,i)=>{if(this.connectionState===pI.CONNECTED)return t();const n=()=>{this.off(_I.WS_CLOSED,r),t();},r=()=>{this.off(_I.WS_CONNECTED,n),i(new LI(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,n),this.once(_I.WS_CLOSED,r),e!==EI.PUBLISH&&e!==EI.SUBSCRIBE&&e!==EI.UNSUBSCRIBE&&e!==EI.UNPUBLISH&&e!==EI.CONTROL&&e!==EI.RESTART_ICE||this.once(_I.DISCONNECT_P2P,()=>{i(new LI(Hg.DISCONNECT_P2P));}),e!==EI.PUBLISH&&e!==EI.RESTART_ICE||this.once(_I.ABORT_P2P_EXECUTION,()=>{i(new LI(Hg.DISCONNECT_P2P));});});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),e===EI.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(s,!0,!1),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new LI(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("dc request timeout, type: ".concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new LI(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new LI(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fv.MULTI_IP)):this.reconnect(u.action,fv.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((i,n)=>{this.once(_I.WS_CONNECTED,()=>i(this.joinResponse)),this.once(_I.WS_CLOSED,()=>n(this.initError||new LI(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(gv.FAILBACK,()=>{void 0===this.openConnectionTime&&n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT));}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData();},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(jC.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new LI(Hg.INIT_DATACHANNEL_TIMEOUT)));},RC("DC_JOIN_WITH_FAILBACK"));});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new Ny("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents());}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.DATACHANNEL_CONNECTING),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}async rejoin(){if(!this.reconnectToken)throw new LI(Hg.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=bT(this,_I.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(EI.REJOIN,e);return !!t&&(this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(fI.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(fI.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(fI.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(fI.MUTE_AUDIO,{uid:e.uid}):this.emit(fI.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(fI.MUTE_VIDEO,{uid:e.uid}):this.emit(fI.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(fI.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(fI.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(fI.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(fI.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id});}),!0);}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fv.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fv.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(mI.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e});}handleWebsocketEvents(){this.websocket.on(gv.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(gv.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(gv.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(gv.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(gv.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(gv.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(gv.WILL_RECONNECT,(e,t)=>{if(bT(this,_I.IS_P2P_DISCONNECTED)&&"retry"===e)return jC.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(jC.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION),this.emit(_I.DISCONNECT_P2P)),t(e);}),this.websocket.on(gv.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{jC.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",fv.SERVER_ERROR);}):this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof LI&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fv.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fv.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(gv.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(gv.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);}),this.websocket.on(gv.TO_CONNECT_DATACHANNEL,async(e,t,i)=>vT(this,_I.DATACHANNEL_PRECONNECT,e).then(t).catch(i)),this.websocket.on(gv.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(_I.DATACHANNEL_FAILBACK);});}}class Py extends dT{constructor(e,t){super(),sh(this,"signal",void 0),sh(this,"token",void 0),sh(this,"tokenTimeout",void 0),sh(this,"tokenInterval",void 0),sh(this,"_sequence",0),sh(this,"userMap",new Map()),sh(this,"encoder",new TextEncoder()),this.signal=e,this.token=t;const i=()=>{this.signal.connectionState===pI.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*RC("P2P_TOKEN_INTERVAL"));};i();}async send(e,t,i,n,r){var s,o,a;if(0===this.userMap.size)return;const c=Array.from(NI(s=this.userMap).call(s))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),n=null!==(o=n)&&void 0!==o?o:nS(6,""),r=null!==(a=r)&&void 0!==a?a:this._sequence++;const d={_id:n,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(c)};RC("SHOW_P2P_LOG")&&jC.debug("send message",d,"noNeedResponse : ".concat(i));this.splitMessage(JSON.stringify(d)).forEach(e=>{this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(e))});});const l=new cg((t,r)=>{const s=window.setTimeout(()=>{this.off("res-@".concat(n,"_ack"),o),this.off("res-@".concat(n),c),this.off(yv.ABORT,a),jC.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(n)),0===this.userMap.size?r(new Kg(Hg.INVALID_REMOTE_USER)):r(new Kg(Hg.TIMEOUT));},RC("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),o=()=>{s&&window.clearTimeout(s),this.off(yv.ABORT,a),i&&t();},a=()=>{s&&window.clearTimeout(s),this.off("res-@".concat(n,"_ack"),o),this.off("res-@".concat(n),c),r(new Kg(Hg.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(n)));};this.once(yv.ABORT,a),this.once("res-@".concat(n,"_ack"),o);const c=(i,c)=>{l=!0,s&&window.clearTimeout(s),this.off("res-@".concat(n,"_ack"),o),this.off(yv.ABORT,a),"success"===i?t(c):r(new Kg(Hg.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(n)));};let l=!1;i||(this.once("res-@".concat(n),c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{l||jC.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(n,", ").concat(d));}));});try{return await l;}catch(s){if(s.code===Hg.TIMEOUT)return await this.send(e,t,i,n,r);throw s;}}onMessage(e){var t;const{_uid:i}=e;let n,r=this.userMap.get(i);if(r)n=r.splitMessageMap;else {if(this.userMap.size>0||!("_type"in e)||e._type!==vv.CHECK)return;const{token:t}=e;n=new Map(),r={uid:i,isStart:!0,token:t,splitMessageMap:n,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map()},this.userMap.set(i,r),this.signal.emit(fI.ON_USER_ONLINE,{uid:i}),this.handleUserOnline();}if("id"in e&&"total"in e){var s;const{id:t,total:r}=e,o=null!==(s=n.get(t))&&void 0!==s?s:[];if(o.push(e),n.has(t)||n.set(t,o),o.length!==r)return;{const r=ep(o).call(o,(e,t)=>e.index-t.index).map(e=>e.payload).join("");n.delete(t),(e=JSON.parse(r))._uid=i;}}const{_type:o,token:a}=e;if(bn(t=[vv.ACK,vv.CHECK]).call(t,o))return o===vv.CHECK&&this.handleCheckToken(r,a),void this.receiveMessage(e);a==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):jC.debug('Receive unexpected message", '.concat(a,", cur_token: ").concat(r.token,"_").concat(this.token),e);}check(){const e={_id:nS(6,""),token:this.token,_type:vv.CHECK};RC("SHOW_P2P_LOG")&&jC.debug("send message",e),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(e)))});}ack(e){const t={_id:e,_type:vv.ACK,token:this.token};RC("SHOW_P2P_LOG")&&jC.debug("send message",t),this.signal.request(EI.DATA_STREAM,{payload:QT(this.encoder.encode(JSON.stringify(t)))});}response(e,t,i){this.send(vv.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e);}handleReceivedMessage(e){const t=()=>{this.userMap.forEach(e=>{const{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){const n=t.get(i);t.delete(i),this.receiveMessage(n),e.nextExpectedSequenceNumber++;}});};if(!e)return void t();const{_uid:i,_seq:n}=e,r=this.userMap.get(i),{receivedMessagesMap:s,isStart:o,nextExpectedSequenceNumber:a}=r;if(n{this.response(e._id,t);}).catch(()=>{this.response(e._id,void 0,!0);});break;case vv.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case vv.RESPONSE:{const{success:e,message:i}=s;this.emit("res-@".concat(t),e?"success":"failed",i);break;}}}}splitMessage(e){if(e.length0;){r++;const a={id:n,index:r,total:o,payload:e.slice(0,s),token:"".concat(this.token,"_").concat(i)};JSON.stringify(a).length>Py.MAX_MESSAGE_SIZE?s-=50:(t.push(a),e=e.slice(s));}return t.map(e=>JSON.stringify(e));}handleCheckToken(e,t){return e.token!==t?(jC.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout(()=>{jC.debug("token timeout, ".concat(t)),this.reset(e.uid);},RC("MAX_P2P_TIMEOUT")),!0);}async handleUserOnline(){const e=await vT(this.signal,vv.CALL,void 0),t=await this.send(vv.CALL,e);this.signal.emit(_I.P2P_CONNECTION,t,!0);}async reset(e,t){const i=this.userMap.get(e);i&&(this.emit(yv.ABORT),this.signal.emit(fI.ON_USER_OFFLINE,{uid:i.uid,reason:wv.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(jC.debug("change local token from ".concat(t," to ").concat(t)),this.token=nS(6,"")));}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(yv.ABORT);}}sh(Py,"MAX_SIZE",1),sh(Py,"MAX_MESSAGE_SIZE",1024);class Ly extends dT{get connectionState(){return this._connectionState;}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===pI.CONNECTED?this.emit(_I.WS_CONNECTED):e===pI.RECONNECTING?this.emit(_I.WS_RECONNECTING,this._websocketReconnectReason):e===pI.CLOSED&&this.emit(_I.WS_CLOSED,this._disconnectedReason));}get currentURLIndex(){return this.websocket.currentURLIndex;}get url(){return this.websocket&&this.websocket.url||null;}get rtt(){return this.rttRolling.mean();}constructor(e,t){super(),sh(this,"_disconnectedReason",void 0),sh(this,"_websocketReconnectReason",void 0),sh(this,"_connectionState",pI.CLOSED),sh(this,"reconnectToken",void 0),sh(this,"p2pToken",void 0),sh(this,"websocket",void 0),sh(this,"openConnectionTime",void 0),sh(this,"clientId",void 0),sh(this,"lastMsgTime",Date.now()),sh(this,"uploadCache",[]),sh(this,"uploadCacheInterval",void 0),sh(this,"rttRolling",new gS(5)),sh(this,"pingpongTimer",void 0),sh(this,"pingpongTimeoutCount",0),sh(this,"joinResponse",void 0),sh(this,"multiIpOption",void 0),sh(this,"initError",void 0),sh(this,"spec",void 0),sh(this,"store",void 0),sh(this,"_external_signal",void 0),sh(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(_I.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message);}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case fI.ON_DATA_STREAM:return void this.handleDataStream(t._message);case fI.MUTE_AUDIO:case fI.MUTE_VIDEO:case fI.ON_P2P_LOST:case fI.ON_USER_ONLINE:return;case fI.ON_USER_OFFLINE:const{uid:e}=t._message;return jC.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e);}if(this.emit(t._type,t._message),t._type===fI.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===fI.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(ET.UID_BANNED);break;case 15:this.close(ET.IP_BANNED);break;case 16:this.close(ET.CHANNEL_BANNED);}if(t._type===fI.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case hI.ERR_LICENSE_MISSING:this.close(ET.LICENSE_MISSING);break;case hI.ERR_LICENSE_EXPIRED:this.close(ET.LICENSE_EXPIRED);break;case hI.ERR_LICENSE_MINUTES_EXCEEDED:this.close(ET.LICENSE_MINUTES_EXCEEDED);break;case hI.ERR_LICENSE_PERIOD_INVALID:this.close(ET.LICENSE_PERIOD_INVALID);break;case hI.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(ET.LICENSE_MULTIPLE_SDK_SERVICE);break;case hI.ERR_LICENSE_ILLEGAL:this.close(ET.LICENSE_ILLEGAL);break;default:this.close();}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===pI.CONNECTED&&this.reconnect("retry",fT.OFFLINE);}),this.p2pToken=nS(6,""),this._external_signal=new Py(this,this.p2pToken);}async request(e,t,i,n){const r=nS(6,""),s={_id:r,_type:e,_message:t},o=this.websocket.connectionID,a=()=>new cg((e,t)=>{if(this.connectionState===pI.CONNECTED)return e();const i=()=>{this.off(_I.WS_CLOSED,n),e();},n=()=>{this.off(_I.WS_CONNECTED,i),t(new Kg(Hg.WS_ABORT));};this.once(_I.WS_CONNECTED,i),this.once(_I.WS_CLOSED,n);});if(this.connectionState!==pI.CONNECTING&&this.connectionState!==pI.RECONNECTING||e===EI.JOIN||e===EI.REJOIN||(await a()),this.websocket.sendMessage(s,!0),n)return;const c=new cg((i,n)=>{let s=!1;const a=(n,r)=>{s=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.emit(_I.REQUEST_SUCCESS,e,t);};this.once("res-@".concat(r),a);const c=()=>{n(new Kg(Hg.WS_ABORT,"type: ".concat(e))),this.off(_I.WS_CLOSED,c),this.off(_I.WS_RECONNECTING,c),this.off("res-@".concat(r),a);};this.once(_I.WS_CLOSED,c),this.once(_I.WS_RECONNECTING,c),iS(RC("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||s||(jC.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(_I.REQUEST_TIMEOUT,e,t));});});let d=null;try{d=await c;}catch(n){if(this.connectionState===pI.CLOSED||e===EI.LEAVE)throw new Kg(Hg.WS_ABORT);return !this.spec.forceWaitGatewayResponse||i?n.throw():e===EI.JOIN||e===EI.REJOIN?null:(await a(),await this.request(e,t));}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=kv(l),h=new Kg(Hg.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return "success"===u.action?d.message:(jC.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===hI.ERR_TOO_MANY_BROADCASTERS?e===EI.JOIN||e===EI.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===hI.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,jC.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",fT.MULTI_IP)):this.reconnect(u.action,fT.SERVER_ERROR),e===EI.JOIN||e===EI.REJOIN?null:await this.request(e,t)));}waitMessage(e,t){return new cg(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r));};this.on(e,n);});}uploadWRTCStats(e){if(!this.store.sessionId)return void jC.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(mI.WRTC_STATS,t);}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i);}catch(e){const t=RC("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==pI.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message);},RC("UPLOAD_CACHE_INTERVAL")||2e3));}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i);}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i);}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cg((t,i)=>{this.once(_I.WS_CONNECTED,()=>t(this.joinResponse)),this.once(_I.WS_CLOSED,()=>i(this.initError||new Kg(Hg.WS_ABORT))),this.connectionState=pI.CONNECTING,this.websocket.init(e).catch(i);});}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||ET.LEAVE,this.connectionState=pI.CLOSED,jC.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===ET.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new qv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,RC("JOIN_GATEWAY_USE_DUAL_DOMAIN"),RC("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents()),this.p2pToken=nS(6,""),this._external_signal.clear(),this._external_signal=new Py(this,this.p2pToken);}async join(){if(!this.joinResponse){this.emit(_I.ABORT_P2P_EXECUTION);const e=await vT(this,_I.REQUEST_JOIN_INFO),t=await this.request(EI.JOIN,e);if(!t)return this.emit(_I.REPORT_JOIN_GATEWAY,Hg.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(_I.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token;}return this.connectionState=pI.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0;}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t);}handleDataStream(e){try{var t;const i=XT(e.payload),n=new TextDecoder().decode(i),r=JSON.parse(n);"total"in r&&"id"in r||bn(t=Object.values(vv)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(fI.ON_DATA_STREAM,e);}catch(t){this.emit(fI.ON_DATA_STREAM,e);}}handleNotification(e){jC.debug("[".concat(this.clientId,"] receive notification: "),e);const t=kv(e.code);if("success"!==t.action){if("failed"!==t.action)return "quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(ET.UID_BANNED),void this.close()):void this.reconnect(t.action,fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] ignore error: "),t.desc);}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=RC("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(jC.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>RC("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",fT.TIMEOUT):this.request(EI.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),RC("REPORT_STATS")&&this.send(EI.PING_BACK,{pingpongElapse:e});}).catch(e=>{});}handleWebsocketEvents(){this.websocket.on(SI.RECONNECT_WAITTING_FINISH,e=>{this.emit(_I.WS_RECONNECT_WAITTING_FINISH,e);}),this.websocket.on(SI.RECONNECT_CREATE_CONNECTION,e=>{this.emit(_I.WS_RECONNECT_CREATE_CONNECTION,e);}),this.websocket.on(SI.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(SI.CLOSED,()=>{this.connectionState=pI.CLOSED;}),this.websocket.on(SI.FAILED,()=>{this._disconnectedReason=ET.NETWORK_ERROR,this.connectionState=pI.CLOSED;}),this.websocket.on(SI.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===pI.CONNECTED?this.connectionState=pI.RECONNECTING:this.connectionState=pI.CONNECTING;}),this.websocket.on(SI.WILL_RECONNECT,(e,t,i)=>{"retry"!==e?(jC.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(_I.NEED_RENEW_SESSION)):jC.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e);}),this.websocket.on(SI.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.join().catch(e=>{if(this.emit(_I.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof Kg&&e.code===Hg.UNEXPECTED_RESPONSE&&e.data.code===hI.ERR_NO_AUTHORIZED)return jC.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",fT.SERVER_ERROR);jC.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",fT.SERVER_ERROR):(this.initError=e,this.close());});}),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,_I.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t);}),this.websocket.on(SI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE);});}}function ky(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function My(e){for(var t=1;t255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(jC.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.apResponse.addresses.some(e=>e.fingerprint)||RC("FINGERPRINT")||(jC.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal();}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const n=Date.now();let r=Uy.get(e.cname);if(r||(r=new Map(),Uy.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new LI(Hg.UID_CONFLICT);throw eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,t;}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=n;const o=e.proxyServer;try{let t;if(jC.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof Dy?"datachannel":"websocket"," join uid ").concat(s)),this.signal instanceof Dy)t=await this.signal.init(e.apResponse.addresses,i);else {const n=e.gatewayAddrs.map(t=>{let{address:i}=t;const[n,r]=i.split(":"),s={host:n,port:r};return e.proxyServer&&(s.proxy=e.proxyServer),s;});t=await this.signal.init(n,i);}s=t.uid,jC.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof Dy?"datachannel":"websocket"," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime));}catch(t){if(t&&t.code===Hg.INIT_WEBSOCKET_TIMEOUT)throw jC.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===Hg.INIT_DATACHANNEL_TIMEOUT)throw jC.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw jC.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),eI.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!o,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t;}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),jC.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{jC.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString());});},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(XI.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:Cy(this._statsCollector.trafficStats.B_dnq)}):this.emit(XI.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0});},2e3),this.store.joinGatewayEnd(),s;}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==ET.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==pI.CONNECTED||(await function(e,t){return t===1/0?e:cg.race([e,tS(t)]);}(this.signal.request(EI.LEAVE,void 0,!0),3e3));}catch(e){jC.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e);}this.signal.close(t),t!==ET.FALLBACK&&(this.state="DISCONNECTED"),this.reset();}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:RC("PUB_EXTEND"),twcc:!!RC("PUBLISH_TWCC"),rtx:!!RC("USE_PUB_RTX")};try{return (await this.signal.request(EI.PUBLISH,n,!0))._message;}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n;}}async publishDataChannel(e,t,i){var n;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(n=t.maxRetransmits)&&void 0!==n?n:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(EI.PUBLISH_DATASTREAM,r,!0);}catch(n){if(i&&n.data&&n.data.code===hI.ERR_PUBLISH_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),n.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw n;}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(EI.UNPUBLISH,{stream_id:t,ortc:e},!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] unpublish warning: "),e);}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cg.all(e.map(e=>this.signal.request(EI.UNPUBLISH_DATASTREAM,{channel_id:e},!0)));}catch(e){jC.warning("unpublish datachannels warning: ",e);}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC("SUBSCRIBE_TWCC"),rtx:!!RC("USE_SUB_RTX")||void 0,extend:RC("SUB_EXTEND"),svc:Array.isArray(RC("SVC"))&&0!==RC("SVC").length?RC("SVC"):void 0};try{return await this.signal.request(EI.PRE_SUBSCRIBE,n,!0);}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),n.toString()),this.presubscribe(e,t,!1);throw n;}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!RC("SUBSCRIBE_TWCC"),rtx:!!RC("USE_SUB_RTX"),extend:RC("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(RC("SVC"))&&0!==RC("SVC").length?RC("SVC"):void 0};try{return (await this.signal.request(EI.SUBSCRIBE,n,!0))._message;}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n;}}async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const n={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void(await this.signal.request(EI.SUBSCRIBE_DATASTREAM,n,!0));}catch(n){if(i&&n.data&&n.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),n.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw n;}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!RC("USE_SUB_RTX")};try{return await this.signal.request(EI.SUBSCRIBE_STREAMS,i,!0);}catch(i){if(t&&i.data&&i.data.code===hI.ERR_SUBSCRIBE_REQUEST_INVALID)return jC.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i;}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return "number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0;}(e);if(t)return this.signal.request(EI.SET_VIDEO_PROFILE,t);jC.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"));}async unsubscribe(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e);}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new LI(Hg.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cg.all(e.map(e=>this.signal.request(EI.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0)));}catch(e){jC.warning("unsubscribeDataChannel warning: ",e);}}async massUnsubscribe(e){try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,e,!0);}catch(e){jC.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e);}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return {gatewayEstablishParams:await this.signal.request(EI.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()};}getGatewayInfo(){return this.signal.request(EI.GATEWAY_INFO);}async renewToken(e){await this.signal.request(EI.RENEW_TOKEN,e),this.key=e.token;}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i,n=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,n=1):n=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:n=0,await this.signal.request(EI.SET_CLIENT_ROLE,{role:e,level:n,delay:i,client_ts:Date.now()}),this.role=e;}async setRemoteVideoStreamType(e,t){await this.signal.request(EI.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t});}async setDefaultRemoteVideoStreamType(e){await this.signal.request(EI.DEFAULT_VIDEO_STREAM,{stream_type:e});}async setStreamFallbackOption(e,t){await this.signal.request(EI.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t});}async pickSVCLayer(e,t){await this.signal.request(EI.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer});}async setRTM2Flag(e){await this.signal.request(EI.SET_RTM2_FLAG,{rtm2_flag:e});}async sendExtensionMessage(e,t,i){if(this.signal instanceof Ly)return this.signal.sendExtensionMessage(e,t,i);}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),My({},this.inChannelInfo);}async getGatewayVersion(){return (await this.signal.request(EI.GATEWAY_INFO)).version;}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=Uy.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid);}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0);}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:iI.username,password:iI.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null;}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(My(My({},iI),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}));}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(EI.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach(e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(t=>t.peer_uid===e.peer_uid);t&&t.B_st!==e.B_st&&KT(()=>{this.emit(XI.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st);});}),this._statsCollector.updateTrafficStats(e);}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new LI(Hg.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=RC("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i);}catch(e){i=void 0;}i&&i.length>128&&(i=void 0);const n=My({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:EC,browser:navigator.userAgent,process_id:RC("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:RC("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:i,attributes:{userAttributes:{enablePublishedUserList:RC("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:RC("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof RC("SUBSCRIBE_AUDIO_FILTER_TOPN")?RC("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof RC("ENABLE_PUBLISH_AUDIO_FILTER")?RC("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof RC("ENABLE_USER_LICENSE_CHECK")?RC("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:!0===RC("USE_PUB_RTX")||!0===RC("USE_SUB_RTX")||void 0,disableFEC:RC("DISABLE_FEC"),enableNTPReport:!!RC("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!RC("ENABLE_INSTANT_VIDEO")||void 0,enableDataStream2:"boolean"==typeof RC("ENABLE_DATASTREAM_2")?RC("ENABLE_DATASTREAM_2"):void 0,rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!RC("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:"boolean"==typeof RC("USE_XR")?RC("USE_XR"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,RC("ENCRYPT_AES")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n;}getRejoinMessage(){if(!this.joinInfo)throw new LI(Hg.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return {session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)};}handleSignalEvents(){this.signal.on(_I.WS_RECONNECT_WAITTING_FINISH,e=>{var t;bn(t=["tryNext","recover"]).call(t,e)&&this.joinInfo&&eI.adjustSessionStartTime(this.joinInfo.sid);}),this.signal.on(_I.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now();}),this.signal.on(_I.WS_RECONNECTING,e=>{this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||fT.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",eI.sessionInit(this.joinInfo.sid,{lts:new Date().getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now());}),this.signal.on(_I.WS_CLOSED,e=>{let t;switch(e){case ET.LEAVE:t=fT.LEAVE;break;case ET.UID_BANNED:case ET.IP_BANNED:case ET.CHANNEL_BANNED:case ET.SERVER_ERROR:t=fT.SERVER_ERROR;break;case ET.FALLBACK:t=fT.FALLBACK;break;case ET.LICENSE_MISSING:case ET.LICENSE_EXPIRED:case ET.LICENSE_MINUTES_EXCEEDED:case ET.LICENSE_PERIOD_INVALID:case ET.LICENSE_MULTIPLE_SDK_SERVICE:case ET.LICENSE_ILLEGAL:case ET.TOKEN_EXPIRE:t=e;break;default:t=fT.NETWORK_ERROR;}jC.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+fT.NETWORK_ERROR)),this.joinInfo&&eI.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===ET.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==ET.FALLBACK&&(this.state="DISCONNECTED"),this.reset();}),this.signal.on(_I.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(jC.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void jC.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));SC("EVENT_REPORT_DOMAIN",e[1]),SC("EVENT_REPORT_BACKUP_DOMAIN",e[1]),SC("LOG_UPLOAD_SERVER","".concat(e[1],":6444"));}}),this.signal.on(fI.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e);}),this.signal.on(_I.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new LI(Hg.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,vT(this,XI.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i);}),this.signal.on(_I.REQUEST_JOIN_INFO,async e=>{var t;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await vT(this,XI.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}));}),this.signal.on(_I.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage());}),this.signal.on(_I.REPORT_JOIN_GATEWAY,(e,t)=>{this.joinInfo&&(eI.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof Dy?"1":"0"}),this._isProactiveJoin=!1);}),this.signal.on(_I.IS_P2P_DISCONNECTED,e=>{e(bT(this,XI.IS_P2P_DISCONNECTED));}),this.signal.on(_I.DISCONNECT_P2P,()=>{this.emit(XI.DISCONNECT_P2P);}),this.signal.on(_I.NEED_RENEW_SESSION,()=>{this.emit(XI.NEED_RENEW_SESSION);}),this.signal.on(_I.REQUEST_SUCCESS,()=>{this._signalTimeout=!1;}),this.signal.on(_I.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0;}),this.signal.on(_I.JOIN_RESPONSE,e=>{const t=this.getCurrentGatewayAddress();this.emit(XI.JOIN_RESPONSE,e,t);}),this.signal.on(_I.DATACHANNEL_PRECONNECT,async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return vT(this,XI.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i);}),this.signal.on(_I.DATACHANNEL_CONNECTING,async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await vT(this,XI.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}));}),this.signal.on(_I.DATACHANNEL_FAILBACK,()=>{jC.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(XI.DATACHANNEL_FAILBACK);});}async tryUnsubBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e;}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(EI.UNSUBSCRIBE,{stream_id:t.id},!0);}catch(e){throw jC.warning("unsubscribe datachannel warning",e),e;}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH,{stream_id:e,ortc:t},!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e;}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(EI.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0);}catch(e){throw jC.warning("unpublish datastream warning: ",e),e;}}async tryMassUnsubBeforeResub(e){const t={users:e.map(e=>({stream_id:e.stream_id,stream_type:e.stream_type}))};try{await this.signal.request(EI.UNSUBSCRIBE_STREAMS,t,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e;}}async muteLocal(e,t){const i={action:e.find(e=>e.stream_type===JI.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e;}}async unmuteLocal(e,t){const i={action:e.find(e=>e.stream_type===JI.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e;}}async muteRemote(e,t){const i={action:e===av.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e;}}async unmuteRemote(e,t){const i={action:e===av.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(EI.CONTROL,i,!0,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e;}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e);}upload(e,t){this.signal.upload(e,t);}getSignalRTT(){return this.signal.rtt;}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(EI.RESTART_ICE,t,!0);}catch(e){throw jC.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e;}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,fT.P2P_FAILED);}getCurrentGatewayAddress(){var e;if(!RC("GATEWAY_WSS_ADDRESS"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0;}async setPublishAudioFilterEnabled(e){await this.signal.request(EI.SET_PARAMETER,{enablePublishAudioFilter:e});}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(ET.FALLBACK)),this.store.useDataChannel=!1,this.signal=new Jv(My(My({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(XI.RESET_SIGNAL,$I.websocket);}}let Vy=0,Fy=0;function By(e,t,i,n){return new cg((r,s)=>{t.timeout=t.timeout||RC("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),Vy+=$T(t.data)):i&&(t.data.size?Vy+=t.data.size:t.data instanceof FormData?Vy+=eS(t.data):Vy+=$T(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,sC.request(t).then(e=>{"string"==typeof e.data?Fy+=$T(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Fy+=e.data.byteLength:Fy+=$T(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data);}).catch(e=>{sC.isCancel(e)?s(new LI(Hg.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new LI(Hg.NETWORK_TIMEOUT,e.message)):e.response?s(new LI(Hg.NETWORK_RESPONSE_ERROR,e.response.status)):s(new LI(Hg.NETWORK_ERROR,e.message));});});}/*! formdata-polyfill. MIT License. Jimmy W?rting */!function(){var e;function i(e){var t=0;return function(){return t>>0)+"_",r=0;return function e(n){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n);};}),o("Symbol.iterator",function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r{const e=RC("AREAS");0===e.length&&e.push(ev.GLOBAL);return BT(e).call(e,(e,t,i)=>{const n=Gy(t);return n?0===i?n:"".concat(e,",").concat(n):e;},"");},Gy=e=>e===ev.OVERSEA?"".concat(nv.ASIA,",").concat(nv.EUROPE,",").concat(nv.AFRICA,",").concat(nv.NORTH_AMERICA,",").concat(nv.SOUTH_AMERICA,",").concat(nv.OCEANIA):nv[e],Wy=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map(e=>{const i=rv[e],n=Object.keys(i);n&&n.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]));});}),t;},Hy={GLOBAL:{ASIA:[ev.CHINA,ev.JAPAN,ev.INDIA,ev.KOREA,ev.HKMC],EUROPE:[],NORTH_AMERICA:[ev.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Ky=Object.keys(Hy[ev.GLOBAL]),Yy=[ev.CHINA,ev.NORTH_AMERICA,ev.EUROPE,ev.ASIA,ev.JAPAN,ev.INDIA,ev.OCEANIA,ev.SOUTH_AMERICA,ev.AFRICA,ev.KOREA,ev.HKMC,ev.US],qy=function(e,t){let i=[];if(bn(e).call(e,ev.GLOBAL)){const s=[ev.GLOBAL,ev.OVERSEA],o=Object.keys(rv);if(t===ev.GLOBAL)throw new LI(Hg.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===ev.CHINA)i=[ev.OVERSEA];else if(r=t,bn(Ky).call(Ky,r)){const e=(n=t,Hy[ev.GLOBAL][n]||[]),r=[...s,t,...e];i=o.filter(e=>!bn(r).call(r,e));}else if(function(e){let t=!1;return Ky.forEach(i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=!0);}),t;}(t)){const e=function(e){let t;return Ky.forEach(i=>{var n;bn(n=Hy[ev.GLOBAL][i]).call(n,e)&&(t=i);}),t;}(t),n=[...s,e,t];i=o.filter(e=>!bn(n).call(n,e));}else i=e;i=function(e){const t=[];return Yy.forEach(i=>{bn(e).call(e,i)&&t.push(i);}),t.concat(e.filter(e=>!bn(Yy).call(Yy,e)));}(i);}else i=e;var n,r;return i;};function zy(e){var t,i;if(!e&&bn(t=RC("AREAS")).call(t,ev.EXTENSIONS))return jC.debug("update area from ap : reset"),void Jy(tI,!0);if(!bn(i=RC("AREAS")).call(i,ev.GLOBAL)||!e)return;let n=rv.EXTENSIONS;n&&(n={CODE:Gy(ev.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},jC.debug("update area from ap success: ".concat(e,",config is "),n),SC("AREAS",[ev.EXTENSIONS],!0),Object.keys(n).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){SC(e,n[e][0]);}else SC(e,n[e]);}));}function Jy(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=eI.reportApiInvoke(null,{name:hT.SET_AREA,options:e,tag:pT.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!bn(iv).call(iv,e))throw new LI(Hg.INVALID_PARAMS,"invalid area code");}),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new LI(Hg.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?qy(r,i):r;}if(!t){if(CC.AREAS){const e=new LI(Hg.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void jC.warning("setArea is prohibited because of config-distribute");}if(bn(n).call(n,ev.GLOBAL)&&RC("AREAS")===ev.EXTENSIONS){const e=new LI(Hg.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void jC.warning("setArea is prohibited because of ap extensions");}}SC("AREAS",n,t);const r=Wy(n);Object.keys(r).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){SC(e,r[e][0]);}else SC(e,r[e]);}),jC.debug("set area success:",n.join(","));}catch(e){throw i.onError(e),e;}i.onSuccess();}function Xy(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Qy(e){for(var t=1;t{a=Date.now();const e=await By(d,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw jC.error(t.toString()),t;}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw jC.error(e.toString()),e;}if(!i.servers||0===i.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw jC.error(e.toString()),e;}const r=function(e,t){return {addressList:e.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(RC("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:e.workerToken,vid:e.vid};}(i,t);return RC("LIVE_STREAMING_ADDRESS")&&(r.addressList=RC("LIVE_STREAMING_ADDRESS")instanceof Array?RC("LIVE_STREAMING_ADDRESS"):[RC("LIVE_STREAMING_ADDRESS")]),Qy(Qy({},r),{},{responseTime:c});},(n,r)=>(eI.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1),(n,r)=>(eI.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==Hg.OPERATION_ABORTED&&n.code!==Hg.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0)),r);}let eA=1;function tA(e,t,i,n){let{url:r,areaCode:s}=e;const o=Date.now();let a;const[c,d]=oA(t,s,[dy.CHOOSE_SERVER]);let l=wT.networkState;return fS(async()=>{l&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),l=wT.networkState;const{data:e,headers:s}=await By(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a="1"===s.http3?1:-1,eI.reportResourceTiming(r,t.sid),nA(e,r,t,o,[dy.CHOOSE_SERVER],a);const d=Iy(e,dy.CHOOSE_SERVER);return rA(d),Ty(d,r);},e=>(e&&eI.joinChooseServer(t.sid,{lts:o,succ:!0,csAddr:r,opid:d,serverList:e.gatewayAddrs.map(e=>e.address),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),isHttp3:a}),!1),e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinChooseServer(t.sid,{lts:o,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[dy.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:l}),isHttp3:a}),jC.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0)),n);}function iA(e,t,i,n){let r,{url:s,areaCode:o,serviceIds:a}=e;const c=Date.now(),[d,l]=oA(t,o,a);let u;return fS(async()=>{u&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),u=wT.networkState;const{data:e,headers:o}=await By(s,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===o.http3?1:-1,eI.reportResourceTiming(s,t.sid),nA(e,s,t,c,a,r);const l=Iy(e,dy.CHOOSE_SERVER),h=Iy(e,"proxy5"===t.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK);return rA(l),{gatewayInfo:Ty(l,s),proxyInfo:h,url:s};},e=>(e.gatewayInfo&&eI.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:s,serverList:e.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,opid:l,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&eI.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:s,turnServerAddrList:e.proxyInfo.addresses.map(e=>e.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1),e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(eI.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:s,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:u})}),jC.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),n);}const nA=(e,t,i,n,r,s)=>{const o=[],a=o=>{4096===o.flag?eI.joinChooseServer(i.sid,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:o.error.message,csIp:o.error.data&&o.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:s}):1048576!==o.flag&&4194304!==o.flag&&4194310!==o.flag||eI.joinWebProxyAP(i.sid,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:o.error.code,eventType:i.cloudProxyServer,unilbsServerIds:r.toString()});};if(e.response_body.forEach(t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)jC.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else {const i={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};o.push(i),a(i);}if(0!==i){const n=Pv(i),r={error:new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?jC.warning(r.error.toString()):o.push(r),a(r);}}),o.length)throw jC.warning("[".concat(i.clientId,"] multi unilbs ").concat(t," failed, ").concat(o.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry)).join(" | "))),new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,o.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!o.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(o.map(e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc;}).filter(e=>!!e))]});},rA=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new LI(Hg.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});RC("AP_AREA")&&(null!==(n=e.detail)&&void 0!==n&&n[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?zy(e.detail[23].toLowerCase()):zy());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t0){jC.debug("assign gateway address to",RC("GATEWAY_ADDRESS"));const t=RC("GATEWAY_ADDRESS").map(t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find(e=>e.ip===t.ip&&e.port===t.port))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return {ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r};});e.addresses=t;}},sA=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=Pv(t.buffer.code);throw new LI(Hg.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry});}return t.buffer.ticket;}throw jC.debug("update ticket request received ap response without response body:",t),new LI(Hg.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1});},oA=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:Qy({6:e.stringUid,11:t,12:RC("USE_NEW_TOKEN")?"1":void 0,22:t},e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};r.request_bodies.forEach(t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}));});const s=new FormData();return s.append("request",JSON.stringify(r)),[s,n];},aA=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map(e=>({ip:e.ip,port:e.port}))}}]},r=new FormData();return r.append("request",JSON.stringify(n)),[r,i];};let cA=0;function dA(e){return cg.all(e.map(e=>e.then(e=>{throw e;},e=>e))).then(e=>{throw e;},e=>e);}const lA=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:s}=e,o=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=o*a,t=e+a;return i.slice(e,t).map(n);})();s&&s.push(...e);try{c=await dA(e);}catch(e){if(d+=a,o++,!(d>=i.length))return void(await l());r(e);}e.forEach(e=>e.cancel());};return await l(),c;};async function uA(e,t,i,n){const r=async function(e,t,i,n){let r=null;const s=[],o=async()=>{const r=RC("WEBCS_DOMAIN").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:jy()})),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),a=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0];},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),a;},a=async()=>{if(await iS(1e3),null!==r)return r;const o=RC("WEBCS_DOMAIN_BACKUP_LIST").map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:jy()})),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map(e=>e.url)}),c=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),tA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0];},promisesCollector:s});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c;};try{return r=await dA([o(),a()]),s.length&&s.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),r;}catch(e){throw e[0];}}(e,t,i,n);return {gatewayInfo:await r};}async function hA(e,t,i,n,r){const s=e.cloudProxyServer;if("disabled"===s){if(!n)return;if(e.useLocalAccessPoint)return await uA(e,t,i,r);if(RC("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:s}=await EA(e,t,i,r);if(e.turnServer&&"auto"!==e.turnServer.mode)return {gatewayInfo:n};const a=s.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:!1,security:!0}));if(r.useP2P){var o;const t=null!==(o=e.uid)&&void 0!==o?o:n.uid,i="glb:".concat(t.toString()),r=await cT(i),c=s.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||iI.tcpport,udpport:e.udpport||iI.udpport,username:i,password:r,forceturn:!1,security:!0}));a.push(...c);}return e.turnServer={mode:"manual",servers:a},{gatewayInfo:n};}return await uA(e,t,i,r);}const{proxyInfo:a,gatewayInfo:c}=await EA(e,t,i,r),d={gatewayInfo:c},l=a.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:iI.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:iI.udpport,username:e.username||iI.username,password:e.password||iI.password,forceturn:"proxy4"!==s,security:"proxy5"===s}));if(r.useP2P){var u;const t=null!==(u=e.uid)&&void 0!==u?u:c.uid,i="glb:".concat(t.toString()),n=await cT(i),r=a.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport||iI.tcpport,udpport:"proxy4"===s?void 0:e.udpport||iI.udpport,username:i,password:n,forceturn:"proxy4"!==s,security:"proxy5"===s}));l.push(...r);}return e.turnServer={mode:"manual",servers:l},jC.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),d;}async function pA(e,t,i,n,r){const s=RC("ACCOUNT_REGISTER").slice(0,RC("AJAX_REQUEST_CONCURRENT"));let o=[];o=t.proxyServer?s.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):s.map(e=>"https://".concat(e,"/api/v1"));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:o});try{const s=await async function(e,t,i,n,r){const s=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await fS(()=>By(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw jC.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:Hg.INVALID_UINT_UID_FROM_STRING_UID,extend:o}),new LI(Hg.INVALID_UINT_UID_FROM_STRING_UID);return eI.reqUserAccount(o.sid,{lts:s,success:!0,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:null,extend:o}),!1;}const r=Pv(i.code);return r.retry&&(a=e[(n+1)%e.length]),eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:i.uid,errorCode:r.desc,extend:o}),r.retry;},(t,i)=>t.code!==Hg.OPERATION_ABORTED&&(eI.reqUserAccount(o.sid,{lts:s,success:!1,serverAddr:a,stringUid:o.string_uid,uid:null,errorCode:t.code,extend:o}),a=e[(i+1)%e.length],!0),r);if(0!==c.code){const e=Pv(c.code);throw new LI(Hg.UNEXPECTED_RESPONSE,e.desc);}return c;}(o,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),s.uid;}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e;}}async function _A(e,t,i){const n=RC("CDS_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config")),r=n.map(n=>function(e,t,i,n){const r=Sg(),s={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:EC,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return fS(()=>By(e,{data:s,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==Hg.OPERATION_ABORTED,n);}(n,e,t,i));let s=null,o=null,a={};try{s=await dA(r);}catch(e){if(e.code===Hg.OPERATION_ABORTED)throw e;o=e;}r.forEach(e=>e.cancel());if(eI.reportApiInvoke(e.sid,{name:hT.REQUEST_CONFIG_DISTRIBUTE,options:{error:o,res:s}}).onSuccess(),s&&s.test_tags)try{a=function(e){if(!e.test_tags)return {};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach(e=>{var i;const r=Ey(i=e.slice(4)).call(i),s=JSON.parse(t[e])[1];n[r]=s;}),n;}(s);}catch(e){}return a;}async function EA(e,t,i,n){const r=RC("PROXY_SERVER_TYPE3"),s=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),"https://".concat(n,"/ap/?url=").concat(e);};let o=null;const a=[],c=async()=>{const r=RC("WEBCS_DOMAIN").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]};}),o=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),c=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0];},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},o),c;},d=async()=>{if(await iS(1e3),null!==o)return o;const r=RC("WEBCS_DOMAIN_BACKUP_LIST").map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):s("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:jy(),serviceIds:[dy.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?dy.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?dy.CLOUD_PROXY:dy.CLOUD_PROXY_FALLBACK]};}),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),d=await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),iA(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0];},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d;};let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=await dA([c(),d()]));}catch(e){throw e[0];}if(a.length&&a.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),!l||!u)throw new LI(Hg.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];bn(r).call(r,t)&&(e.proxyServer=t,jC.setProxyServer(t),eI.setProxyServer(t));}return o={gatewayInfo:l,proxyInfo:await vy(u,l.uid)},o;}async function mA(e,t,i,n){const r=RC("UAP_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"));return await $y(r,e,t,i,n);}async function fA(e,t,i){const n=RC("UAP_AP").slice(0,RC("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap")),r=n.map(n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:EC,cname:t.cname,uid:t.uid.toString(),requestId:eA,seq:eA};eA+=1;const s={service_name:"tele_channel",json_body:JSON.stringify(r)};return fS(async()=>{const t=await By(e,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw jC.error(e.toString()),e;}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw jC.error(e.toString()),e;}if(!n.servers||0===n.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw jC.error(e.toString()),e;}return {vid:n.vid,workerToken:n.workerToken,addressList:(RC("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(RC("WORKER_DOMAIN"),":").concat(e.wss))};},void 0,e=>!!(e.code!==Hg.OPERATION_ABORTED&&e.code!==Hg.UNEXPECTED_RESPONSE||e.data&&e.data.retry),n);}(n,e,t,i));try{const e=await dA(r);return r.forEach(e=>e.cancel()),e;}catch(e){throw e[0];}}async function gA(e,t,i){let n=null;const r=[],s=async s=>{const o=RC(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"));return s&&(await iS(1e3),null!==n)?n:await lA({fragementLength:RC("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:n=>(jC.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=aA(t,[dy.CHOOSE_SERVER]);let s=wT.networkState;return fS(async()=>{s&&wT.networkState===gT.OFFLINE&&wT.onlineWaiter&&(await cg.race([wT.onlineWaiter,iS(n&&n.maxRetryTimeout||ES.maxRetryTimeout)])),s=wT.networkState;const t=await By(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return sA(t,e);},()=>!1,e=>e.code!==Hg.OPERATION_ABORTED&&(e.code===Hg.UPDATE_TICKET_FAILED?e.data.retry:(jC.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0)),n);}(n,e,t,i)),allFailedhandler:e=>{throw e[0];},promisesCollector:r});};try{return n=await dA([s(!1),s(!0)]),r.length&&r.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),n;}catch(e){throw e[0];}}function TA(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function SA(e){for(var t=1;t{this.updateConfigDistribute();},RC("CONFIG_DISTRIBUTE_INTERVAL")));}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0;}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())();}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;eI.reportApiInvoke(null,{options:void 0,name:hT.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:pT.TRACER}).onSuccess(JSON.stringify(CC));}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void jC.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await _A(this.joinInfo,this.cancelToken,this.retryConfig),jC.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e;}catch(e){const t=new LI(Hg.NETWORK_RESPONSE_ERROR,e);jC.warning("[config-distribute] ".concat(t.toString()));}finally{t();}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0;}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(sv.UPDATE_BITRATE_LIMIT,e):this.emit(sv.UPDATE_BITRATE_LIMIT,e));}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&SA({},this.configs.limit_bitrate.low_stream_uplink);}cacheGlobalParameterConfig(e){var t;const i=ep(t=Object.keys(e).filter(e=>/^webrtc_ng_global_parameter/.test(e))).call(t);for(let t=0;tt;n--){const t=i[n];if("number"==typeof e[t].__priority){const r=e[t].__priority,s=i[n-1];if("number"==typeof e[s].__priority){if(!(r>e[s].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e;}}else {const e=t;i[n]=i[n-1],i[n-1]=e;}}}const n={};i.forEach(t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach(e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=SA({value:i[e]},r&&{expires:r}));});});try{!function(e){try{const t=Date.now();Object.keys(e).forEach(i=>{switch(i){case"ENABLE_EVENT_REPORT":case"UPLOAD_LOG":if(Object.prototype.hasOwnProperty.call(TC,i)){const{value:n,expires:r}=e[i];if(r&&r<=t)return;CC[i]=n,TC[i]=n,jC.debug("Update global parameters from config distribute",i,n);}}});}catch(t){jC.error("Error update config immediately: ".concat(e),t.message);}}(n);const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),jC.debug("Caching global parameters ".concat(e));}catch(e){jC.error("Error caching global parameters:",e.message);}}}const CA={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1};function IA(){return CA;}var vA;function yA(e,t,i){return {sampleRate:e,stereo:t,bitrate:i};}function AA(e,t,i,n,r){return {width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r};}function bA(e,t,i,n,r){return {width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r};}function wA(e,t){return {numSpatialLayers:e,numTemporalLayers:t};}!function(e){e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change";}(vA||(vA={}));const OA={"90p":AA(160,90),"90p_1":AA(160,90),"120p":AA(160,120,15,30,65),"120p_1":AA(160,120,15,30,65),"120p_3":AA(120,120,15,30,50),"120p_4":AA(212,120),"180p":AA(320,180,15,30,140),"180p_1":AA(320,180,15,30,140),"180p_3":AA(180,180,15,30,100),"180p_4":AA(240,180,15,30,120),"240p":AA(320,240,15,40,200),"240p_1":AA(320,240,15,40,200),"240p_3":AA(240,240,15,40,140),"240p_4":AA(424,240,15,40,220),"360p":AA(640,360,15,80,400),"360p_1":AA(640,360,15,80,400),"360p_3":AA(360,360,15,80,260),"360p_4":AA(640,360,30,80,600),"360p_6":AA(360,360,30,80,400),"360p_7":AA(480,360,15,80,320),"360p_8":AA(480,360,30,80,490),"360p_9":AA(640,360,15,80,800),"360p_10":AA(640,360,24,80,800),"360p_11":AA(640,360,24,80,1e3),"480p":AA(640,480,15,100,500),"480p_1":AA(640,480,15,100,500),"480p_2":AA(640,480,30,100,1e3),"480p_3":AA(480,480,15,100,400),"480p_4":AA(640,480,30,100,750),"480p_6":AA(480,480,30,100,600),"480p_8":AA(848,480,15,100,610),"480p_9":AA(848,480,30,100,930),"480p_10":AA(640,480,10,100,400),"720p":AA(1280,720,15,120,1130),"720p_auto":AA(1280,720,30,900,3e3),"720p_1":AA(1280,720,15,120,1130),"720p_2":AA(1280,720,30,120,2e3),"720p_3":AA(1280,720,30,120,1710),"720p_5":AA(960,720,15,120,910),"720p_6":AA(960,720,30,120,1380),"1080p":AA(1920,1080,15,120,2080),"1080p_1":AA(1920,1080,15,120,2080),"1080p_2":AA(1920,1080,30,120,3e3),"1080p_3":AA(1920,1080,30,120,3150),"1080p_5":AA(1920,1080,60,120,4780),"1440p":AA(2560,1440,30,120,4850),"1440p_1":AA(2560,1440,30,120,4850),"1440p_2":AA(2560,1440,60,120,7350),"4k":AA(3840,2160,30,120,8910),"4k_1":AA(3840,2160,30,120,8910),"4k_3":AA(3840,2160,60,120,13500)},NA=[{scaleResolutionDownBy:2,width:1280,height:720,frameRate:30,bitrateMin:300,bitrateMax:900},{scaleResolutionDownBy:1.333333,width:1280,height:720,frameRate:30,bitrateMin:600,bitrateMax:2e3},{scaleResolutionDownBy:1,width:1280,height:720,frameRate:30,bitrateMin:900,bitrateMax:3e3}],DA={"480p":bA(640,480,5),"480p_1":bA(640,480,5),"480p_2":bA(640,480,30),"480p_3":bA(640,480,15),"720p":bA(1280,720,5),"720p_auto":AA(1280,720,30,900,3e3),"720p_1":bA(1280,720,5),"720p_2":bA(1280,720,30),"720p_3":bA(1280,720,15),"1080p":bA(1920,1080,5),"1080p_1":bA(1920,1080,5),"1080p_2":bA(1920,1080,30),"1080p_3":bA(1920,1080,15)},PA={"1SL1TL":wA(1,1),"3SL3TL":wA(3,3),"2SL3TL":wA(2,3)};function LA(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},OA[e]):e;}function kA(e){return "string"==typeof e?Object.assign({},DA[e]):e;}function MA(e){return "string"==typeof e?Object.assign({},PA[e]):e;}const UA={speech_low_quality:yA(16e3,!1),speech_standard:yA(32e3,!1,18),music_standard:yA(48e3,!1),standard_stereo:yA(48e3,!0,56),high_quality:yA(48e3,!1,128),high_quality_stereo:yA(48e3,!0,192)};function xA(e){return "string"==typeof e?Object.assign({},UA[e]):e;}const VA=[];function FA(e){return qg(e,"mediaSource",["screen","window","application"]),!0;}var BA,jA,GA,WA,HA,KA,YA,qA,zA,JA;!function(e){e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track";}(BA||(BA={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream";}(jA||(jA={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM";}(GA||(GA={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM";}(WA||(WA={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY";}(HA||(HA={})),function(e){e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received";}(KA||(KA={})),function(e){e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed";}(YA||(YA={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed";}(qA||(qA={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source";}(zA||(zA={})),function(e){e.UPDATE_TRACK_SOURCE="update-track-source";}(JA||(JA={}));const XA={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},QA={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},ZA={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},$A={uplinkNetworkQuality:0,downlinkNetworkQuality:0},eb={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var tb,ib,nb,rb,sb,ob;!function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node";}(tb||(tb={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints";}(ib||(ib={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND";}(nb||(nb={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged";}(rb||(rb={})),function(e){e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata";}(sb||(sb={})),function(e){e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen";}(ob||(ob={}));const ab={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};var cb;!function(e){e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error";}(cb||(cb={}));class db extends dT{constructor(e,t){super(),sh(this,"_ID",void 0),sh(this,"_rtpTransceiver",void 0),sh(this,"_lowRtpTransceiver",void 0),sh(this,"_hints",[]),sh(this,"_isClosed",!1),sh(this,"_originMediaStreamTrack",void 0),sh(this,"_mediaStreamTrack",void 0),sh(this,"_external",{}),this._ID=t||nS(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){bn(VA).call(VA,e)||VA.push(e);}(this);}toString(){return this._ID;}getTrackId(){return this._ID;}getMediaStreamTrack(e){if(!e){const e=eI.reportApiInvoke(null,{name:hT.GET_MEDIA_STREAM_TRACK,options:[],tag:pT.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("");}return this._mediaStreamTrack;}getRTCRtpTransceiver(e){return e===GA.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver;}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings();}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=VA.indexOf(e);-1!==t&&VA.splice(t,1);}(this),this.emit(YA.CLOSED),this.removeAllListeners(KA.SEI_RECEIVED);}_updateRtpTransceiver(e,t){if(t===GA.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e;}else {if(this._rtpTransceiver===e)return;this._rtpTransceiver=e;}this.emit(KA.TRANSCEIVER_UPDATED,e,t);}}class lb extends db{get isExternalTrack(){return this._isExternalTrack;}get muted(){return this._muted;}get enabled(){return this._enabled;}get processorContext(){return this._processorContext;}constructor(e,t){super(e,t),sh(this,"_enabled",!0),sh(this,"_muted",!1),sh(this,"_isExternalTrack",!1),sh(this,"_isClosed",!1),sh(this,"_enabledMutex",void 0),sh(this,"processor",void 0),sh(this,"_handleTrackEnded",()=>{this.onTrackEnded();}),this._enabledMutex=new pS("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded);}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:"";}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,jC.debug("[".concat(this.getTrackId(),"] close")),this.emit(BA.NEED_CLOSE),super.close());}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}));}_getDefaultPlayerConfig(){return {};}onTrackEnded(){jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}stateCheck(e,t){if(jC.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Yg(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",jC);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Kg(Hg.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",jC);}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[];}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():cg.resolve([]);}}function ub(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const hb=window.AudioContext||window.webkitAudioContext;let pb=null;const _b=new class extends dT{constructor(){super(...arguments),sh(this,"prevState",void 0),sh(this,"curState",void 0),sh(this,"currentTime",void 0),sh(this,"currentTimeStuckAt",void 0),sh(this,"interruptDetectorTrack",void 0),sh(this,"onLocalAudioTrackMute",()=>{jC.info("ios15-interruption-start"),this.emit(vA.IOS_15_16_INTERRUPTION_START);}),sh(this,"onLocalAudioTrackUnmute",async()=>{jC.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?jC.info("ios15-interruption-end-canceled"):(pb&&(await pb.suspend()),this.emit(vA.IOS_15_16_INTERRUPTION_END));});}get duringInterruption(){return "running"===this.prevState&&"interrupted"===this.curState;}bindInterruptDetectorTrack(e){jC.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute);}unbindInterruptDetectorTrack(e){jC.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0);}}();function Eb(){if(!hb)return void jC.error("your browser is not support web audio");jC.info("create audio context");const e=function(e){for(var t=1;t{_b.prevState=_b.curState,_b.curState=pb?pb.state:void 0;const{prevState:e,curState:t}=_b,i="running"===t,n="interrupted"===t,r="running"===e,s="suspended"===e,o="interrupted"===e,a=Sg().osVersion;(Og()||Vg())&&r&&n&&(jC.info("ios".concat(a,"-interruption-start")),_b.emit(vA.IOS_INTERRUPTION_START)),(Og()||Vg())&&(s||o)&&i&&(jC.info("ios".concat(a,"-interruption-end")),_b.emit(vA.IOS_INTERRUPTION_END)),e!==t&&_b.emit(vA.STATE_CHANGE,t,e);},setInterval(()=>{var e;const t=null===(e=pb)||void 0===e?void 0:e.currentTime;if(_b.currentTime!==t)_b.currentTimeStuckAt&&(jC.debug("AudioContext current time resume at ".concat(t)),_b.currentTimeStuckAt=void 0),_b.currentTime=t;else {if(t!==_b.currentTimeStuckAt){eI.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:pT.TRACER}).onSuccess(),jC.warning("AudioContext current time stuck at ".concat(t));}_b.currentTimeStuckAt=t;}},5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,s=!1;function o(t){"running"===e.state?a(!1):Og()||Vg()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d));}function a(e){if(n!==e){n=e;for(let i=0,n=t;i",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,u(!0);}_b.on(vA.STATE_CHANGE,c),o(!1);}(pb);}function mb(){if(!pb){if(Eb(),!pb)throw new Kg(Hg.NOT_SUPPORTED,"can not create audio context");return pb;}return pb;}function fb(e){if(function(){if(null!==gb)return gb;const e=mb(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i);}catch(e){r=!0;}return t.disconnect(),gb=r,r;}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>{var s;return e._inputNodes||(e._inputNodes=[]),bn(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e;},e.disconnect=(n,r,s)=>{i.call(e),n?WT(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i);};}let gb=null;function Tb(e,t){let i=!1;const n=1/t;if(RC("DISABLE_WEBAUDIO")){const t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3);},1e3*n);}else {const t=mb();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const s=()=>{if(i)return void(r=null);const o=t.createOscillator();o.onended=s,o.connect(r),o.start(0),o.stop(t.currentTime+n),e(t.currentTime);};s();}return ()=>{i=!0;};}class Sb{constructor(){sh(this,"context",void 0),sh(this,"analyserNode",void 0),sh(this,"sourceNode",void 0),this.context=mb(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4;}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode);}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode);}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||Og()||Vg()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else {const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;ie+t*t,0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100;}getAnalyserNode(){return this.analyserNode;}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode);}catch(e){jC.warning("rebuild analyser node failed.");}}destroy(){this.updateSource(void 0);}}class Rb extends dT{get processSourceNode(){return this.sourceNode;}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode);}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect();}}get processedNode(){return this._processedNode;}constructor(){super(),sh(this,"outputNode",void 0),sh(this,"outputTrack",void 0),sh(this,"isPlayed",!1),sh(this,"context",void 0),sh(this,"audioBufferNode",void 0),sh(this,"destNode",void 0),sh(this,"audioOutputLevel",0),sh(this,"volumeLevelAnalyser",void 0),sh(this,"_processedNode",void 0),sh(this,"playNode",void 0),sh(this,"isDestroyed",!1),sh(this,"onNoAudioInput",void 0),sh(this,"isNoAudioInput",!1),sh(this,"_noAudioInputCount",0),this.context=mb(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),fb(this.outputNode),this.volumeLevelAnalyser=new Sb();}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(zA.ON_AUDIO_BUFFER,function(e){for(let t=0;t{_b.emit("autoplay-failed");}),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode);}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode);}catch(e){}this.isPlayed=!1;}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel();}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Og()||Vg()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e{if(jC.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&(await this.checkHasAudioInput()),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void jC.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>jC.info("resume success")),jC.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),fb(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput();}),"audio"!==e.kind)throw new Kg(Hg.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),fb(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,jC.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));fb(t),this.originVolumeLevelAnalyser=new Sb(),this.originVolumeLevelAnalyser.updateSource(t);}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const s=Sg();t&&s.os===_g.IOS&&Number(null===(n=s.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(_b.on(vA.STATE_CHANGE,()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio();}),this.checkHasAudioInput().then(e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0);}));}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),fb(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(zA.UPDATE_SOURCE),this.audioElement.srcObject=t;}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),_b.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy();}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]));}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),jC.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));fb(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i);}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel();}}async function Ib(e,t,i){const n=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:n(t.height,1080),maxWidth:n(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r);}async function vb(e,t){const i=await yb(e.mediaSource),{sourceId:n,audio:r}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new cg((i,n)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const s=document.createElement("div");s.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",n(e);};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked;},u.appendChild(e),u.appendChild(t);}c.appendChild(u),c.appendChild(d),s.appendChild(o),s.appendChild(a),s.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(s),document.body.appendChild(h),e.map(e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;try{const{width:e}=n.getSize();e>1920&&(n=n.resize({width:1920}));}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e;}t.innerHTML='
'+e.name.replace(/[\u00A0-\u9999<>\&]/g,function(e){return "&#"+e.charCodeAt(0)+";";})+"",t.onclick=()=>{document.body.removeChild(h),i({sourceId:e.id,audio:l});},a.appendChild(t);}});});}(i,t);return await Ib(n,e,r);}async function yb(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=uT();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new Kg(Hg.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t});}catch(e){n=null;}n&&n.then||(n=new cg((e,n)=>{i.desktopCapturer.getSources({types:t},(t,i)=>{t?n(t):e(i);});}));try{return await n;}catch(e){throw new Kg(Hg.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString());}}function Ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const bb=new pS("safari");let wb=!1,Ob=!1;async function Nb(e,t){let i=0,n=null;for(;i<2;)try{n=await Db(e,t,i>0);break;}catch(e){if(e instanceof Kg)throw jC.error("[".concat(t,"] ").concat(e.toString())),e;const n=Pb(e.name||e.code||e,e.message);if(n.code===Hg.MEDIA_OPTION_INVALID){jC.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await iS(500);continue;}throw jC.error("[".concat(t,"] ").concat(n.toString())),n;}if(!n)throw new Kg(Hg.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n;}async function Db(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Kg(Hg.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const n=IA(),r=new MediaStream();if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return jC.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(uT()){if(e.screen.sourceId){Lb(r,await Ib(e.screen.sourceId,e.screen,e.screenAudio));}else {Lb(r,await vb(e.screen,e.screenAudio));}}else if(Ag()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new Kg(Hg.NOT_SUPPORTED,"This browser does not support screen sharing");jC.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(o=e.screen.extensionId,a=t,new cg((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},i=>{if(!i||!i.streamId)return jC.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new Kg(Hg.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId);});}catch(e){jC.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(o,")"),e.toString()),t(new Kg(Hg.CHROME_PLUGIN_NOT_INSTALL));}}));e.screen.mandatory.chromeMediaSourceId=i;Lb(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}));}else if(n.getDisplayMedia){var s;e.screen.mediaSource&&FA(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(s=e.screen.displaySurface)&&void 0!==s?s:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};!n&&delete c.selfBrowserSurface,!o&&delete c.surfaceSwitching,!a&&delete c.systemAudio,jC.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));const d=await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(RC("ENUMERATE_DEVICES_INTERVAL")||(Gg()||Rg()===_g.HARMONY_OS)&&jg())&&this.updateDevicesInfo();},RC("ENUMERATE_DEVICES_INTERVAL_TIME"));}).catch(e=>jC.error(e.toString()));}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices){return new Kg(Hg.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();}const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let s=!this.isAccessMicrophonePermission&&e,o=!this.isAccessCameraPermission&&t;r.audio&&(s=!1),r.video&&(o=!1);let a=null,c=null,d=null;if(!i&&(s||o)){if(bb.isLocked){jC.debug("[device manager] wait GUM lock");(await bb.lock())(),jC.debug("[device manager] GUM unlock");}if(wb&&(s=!1,this.isAccessMicrophonePermission=!0),Ob&&(o=!1,this.isAccessCameraPermission=!0),jC.debug("[device manager] check media device permissions",e,t,s,o),s&&o){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0;}else if(s){try{a=await navigator.mediaDevices.getUserMedia({audio:e});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessMicrophonePermission=!0;}else if(o){try{c=await navigator.mediaDevices.getUserMedia({video:t});}catch(e){const t=Pb(e.name||e.code||e,e.message);if(t.code===Hg.PERMISSION_DENIED)throw t;jC.warning("getUserMedia failed in getDevices",t);}this.isAccessCameraPermission=!0;}jC.debug("[device manager] mic permission",e,"cam permission",t);}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null,e;}catch(e){a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null;return new Kg(Hg.ENUMERATE_DEVICES_FAILED,e.toString()).throw();}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!0,!1,e)).filter(e=>"audioinput"===e.kind);}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!1,!0,e)).filter(e=>"videoinput"===e.kind);}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return (await this.enumerateDevices(!0,!1,e)).filter(e=>"audiooutput"===e.kind);}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach(i=>{i.device.label===e&&(t=i.device.deviceId);}),t;}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find(t=>t.deviceId===e);if(!t)throw new Kg(Hg.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t;}async init(){this.state=nb.INITING;try{await this.updateDevicesInfo(),this.state=nb.INITEND;}catch(e){if(jC.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=nb.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)){new Kg(Hg.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw();}throw e;}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find(e=>"audioinput"===e.kind&&"default"===e.deviceId),i=e.find(e=>"audiooutput"===e.kind&&"default"===e.deviceId);t&&i?i.groupId===t.groupId?jC.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):jC.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):jC.debug("[device-check] default input or output not found");}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach(e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n);}n&&(n.updateAt=t);}),this.deviceInfoMap.forEach((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e));}),this.state!==nb.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach(e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(rb.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(rb.PLAYOUT_DEVICE_CHANGED,e);}}),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0);}checkMediaDeviceInfoIsOk(e){const t=e.filter(e=>"audioinput"===e.kind),i=e.filter(e=>"videoinput"===e.kind),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break;}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break;}return n;}}();let Mb=!1;const Ub=new class extends dT{constructor(){super(...arguments),sh(this,"onAutoplayFailed",void 0),sh(this,"onAudioAutoplayFailed",void 0);}}();function xb(){if(Sg(),!Mb){const e=t=>{t.preventDefault(),Mb=!1,Wg()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0));};Mb=!0,Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),jC.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Ub.onAutoplayFailed?Ub.onAutoplayFailed():Ub.onAudioAutoplayFailed?jC.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):jC.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Ub.emit("autoplay-failed");}}function Vb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Fb(e){for(var t=1;t{Array.from(this.elementMap.entries()).forEach(t=>{let[i,n]=t;const r=this.elementStateMap.get(i),s=n.srcObject.getAudioTracks()[0],o=s&&s.readyState;if(jC.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(o," ").concat(e)),"live"===o){if(e)return n.pause(),void n.play();if("running"===_b.curState)return Mg()?(n.pause(),void n.play()):void(r&&"paused"===r&&n.play());}});}),sh(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(jC.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play());});}),this.autoResumeAudioElement(),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),_b.on(vA.STATE_CHANGE,()=>{Og()&&"suspended"===_b.prevState&&"running"===_b.curState&&this.autoResumeAfterInterruption();});}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t);}catch(e){throw new Kg(Hg.PERMISSION_DENIED,"can not set sink id: "+e.toString());}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,sb.INIT),this.setVolume(t,i);const s=this.sinkIdMap.get(t);if(s)try{r.setSinkId(s).catch(e=>{jC.warning("[".concat(t,"] set sink id failed"),e.toString());});}catch(e){jC.warning("[".concat(t,"] set sink id failed"),e.toString());}const o=r.play();o&&o.then&&o.catch(e=>{n&&Bb(n,"audio",e.message,t),jC.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(jC.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),KT(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),xb();}));});}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]));}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e);}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100);}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e);}bindAudioElementEvents(e,t){jb.forEach(i=>{t.addEventListener(i,i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(jC.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&jC.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message));}this.elementStateMap.set(e,r);});});}getPlayerState(e){return this.elementStateMap.get(e)||"uninit";}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach(e=>{e.play().then(e=>{jC.debug("Auto resume audio element success");}).catch(e=>{jC.warning("Auto resume audio element failed!",e);});}),this.elementsNeedToResume=[];};new cg(e=>{document.body?e():window.addEventListener("load",()=>e());}).then(()=>{Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0));});}}();function Wb(){return function(e,t,i){const n=i.value;return "function"==typeof n&&(i.value=function(){this._isClosed&&new Kg(Hg.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",jC);for(var e=arguments.length,t=new Array(e),i=0;i{r.then(e).catch(t);}):r;}),i;};}function Hb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Kb(e){for(var t=1;ti.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i});}unregisterStats(e,t){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1);}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s});}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message));}return e;}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t});}unregisterUsage(e){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1);}async gatherUsage(){const e=[];if(!this.chained)return [];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}));}catch(e){jC.error("gather extension usage error",e);}return e;}getDirection(){return this.direction;}}class zb extends dT{constructor(e){super(),sh(this,"name","AudioProcessorDestination"),sh(this,"ID","0"),sh(this,"inputTrack",void 0),sh(this,"inputNode",void 0),sh(this,"audioProcessorContext",void 0),sh(this,"_source",void 0),this.audioProcessorContext=e;}get kind(){return "audio";}get enabled(){return !0;}pipe(){throw new Kg(Hg.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor");}unpipe(){throw new Kg(Hg.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor");}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(tb.ON_TRACK,void 0),this.emit(tb.ON_NODE,void 0);}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(tb.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(tb.ON_NODE,this.inputNode));}}class Jb extends dT{set chained(e){this._chained=e;}get chained(){return this._chained;}constructor(e,t,i){super(),sh(this,"constraintsMap",new Map()),sh(this,"statsRegistry",[]),sh(this,"audioContext",void 0),sh(this,"trackId",void 0),sh(this,"direction",void 0),sh(this,"usageRegistry",[]),sh(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i;}async getConstraints(){return vT(this,ib.REQUEST_CONSTRAINTS);}getAudioContext(){return this.audioContext;}async requestApplyConstraints(e,t){var i;return jC.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(i=this.constraintsMap).call(i)));}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),yT(this,ib.REQUEST_UPDATE_CONSTRAINTS,Array.from(NI(t=this.constraintsMap).call(t)));}registerStats(e,t,i){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i});}unregisterStats(e,t){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1);}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const s=r();e.push({processorID:t,processorName:i,type:n,stats:s});}catch(e){jC.error(new Kg(Hg.UNEXPECTED_ERROR,e.message));}return e;}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t});}unregisterUsage(e){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1);}async gatherUsage(){const e=[];if(!this.chained)return [];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof cg&&(i=await i),e.push(Kb(Kb({},i),{},{direction:this.direction}));}catch(e){jC.error("gather extension usage error",e);}return e;}getDirection(){return this.direction;}}class Xb extends dT{get isPlayed(){return !0;}get isFreeze(){return !1;}constructor(){super(),sh(this,"context",void 0),sh(this,"processSourceNode",void 0),sh(this,"outputTrack",void 0),sh(this,"processedNode",void 0),sh(this,"clonedTrack",void 0),sh(this,"outputNode",void 0),this.outputNode=new Qb();}setVolume(){}createOutputTrack(){throw new Kg(Hg.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled");}getOriginVolumeLevel(){return 0;}getAccurateVolumeLevel(){return 0;}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class Qb{disconnect(){}connect(){}}function Zb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function $b(e){for(var t=1;tthis.initWebAudio()):this.initWebAudio();}setVolume(e){zg(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Gb.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void jC.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,yT(this,BA.NEED_REPLACE_TRACK,this).then(()=>{jC.debug("[".concat(this.getTrackId(),"] replace web audio track success"));}).catch(e=>{jC.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e);}));}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel();}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new Kg(Hg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Gb.setSinkID(this.getTrackId(),e);}async setEnabled(e,t,i){return this._setEnabled(e,t,i);}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await yT(this,BA.NEED_ENABLE_TRACK,this),jC.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"));}catch(e){throw i||(this._enabled=!1),jC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e;}}else {this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw i||(this._enabled=!0),jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this));}getStats(){JT(()=>{jC.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead");},"localAudioTrackGetStatsWarning");const e=AT(this,BA.GET_STATS);return e||$b({},XA);}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,t=>e(t));}play(){jC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(jC.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play();}stop(){jC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop();}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy();}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack);}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e));}renewMediaStreamTrack(e){return cg.resolve(void 0);}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e;}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset();}bindProcessorDestinationEvents(e){e.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this));}),e.on(tb.ON_NODE,e=>{this._source.processedNode=e;});}unbindProcessorDestinationEvents(e){e.removeAllListeners(tb.ON_TRACK),e.removeAllListeners(tb.ON_NODE);}bindProcessorContextEvents(e){e.on(ib.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings());});}unbindProcessorContextEvents(e){e.removeAllListeners(ib.REQUEST_CONSTRAINTS);}initWebAudio(){return this._trackSource instanceof Xb&&(this._trackSource=new Cb(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource;}initProcessor(){const e=new Jb(this._source.context,this.getTrackId(),"local"),t=new zb(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(zA.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e});}),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Gb.stop(this.getTrackId()),this._source.play()),yT(this,BA.NEED_REPLACE_MIXING_TRACK,this).then(()=>{jC.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"));}).catch(e=>{jC.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e);})),{processorContext:e,processorDestination:t};}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],ew.prototype,"setVolume",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],ew.prototype,"setPlaybackDevice",null),DI([_S("LocalAudioTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object,Boolean]),PI("design:returntype",cg)],ew.prototype,"setEnabled",null),DI([_S("LocalAudioTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],ew.prototype,"setMuted",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Object)],ew.prototype,"getStats",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",void 0)],ew.prototype,"setAudioFrameCallback",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"stop",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"close",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],ew.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],ew.prototype,"unpipe",null);class tw extends ew{get __className__(){return "MicrophoneAudioTrack";}constructor(e,t,i,n){super(e,t.encoderConfig?xA(t.encoderConfig):{},n,RC("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),sh(this,"_config",void 0),sh(this,"_deviceName","default"),sh(this,"_constraints",void 0),sh(this,"_originalConstraints",void 0),sh(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Mg()||Ug())&&_b.bindInterruptDetectorTrack(this);}async setDevice(e){if(jC.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.audio=$b({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId());}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Nb({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e;}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"));}async setEnabled(e,t,i){if(t)return jC.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e;}return;}const r=$b({},this._constraints),s=kb.searchDeviceIdByName(this._deviceName);s&&!r.deviceId&&(r.deviceId=s);try{i||(this._enabled=!0);const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw i||(this._enabled=!1),jC.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled success"));}close(){super.close(),(Mg()||Ug())&&_b.unbindInterruptDetectorTrack(this);}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0));};_b.on(vA.IOS_INTERRUPTION_END,e);}else jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Nb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0);}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(ib.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t();}catch(e){i(e);}});}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],tw.prototype,"setDevice",null),DI([_S("MicrophoneAudioTrack","_enabledMutex"),$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean,Boolean]),PI("design:returntype",cg)],tw.prototype,"setEnabled",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],tw.prototype,"close",null);class iw extends ew{get __className__(){return "BufferSourceAudioTrack";}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),sh(this,"source",void 0),sh(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(zA.AUDIO_SOURCE_STATE_CHANGE,e=>{this.safeEmit(YA.SOURCE_STATE_CHANGE,e);});try{this._mediaStreamTrack=this._source.createOutputTrack();}catch(e){}}get currentState(){return this._bufferSource.currentState;}get duration(){return this._bufferSource.duration;}get playbackSpeed(){return this._bufferSource.playbackSpeed;}getCurrentTime(){return this._bufferSource.currentTime;}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer();}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer();}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e);}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer();}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer();}close(){this.source=null,this._bufferSource.destroy(),super.close();}setAudioBufferPlaybackSpeed(e){zg(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],iw.prototype,"startProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"pauseProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],iw.prototype,"seekAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"resumeProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"stopProcessAudioBuffer",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],iw.prototype,"close",null),DI([$C({argsMap:e=>[e.getTrackId()]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],iw.prototype,"setAudioBufferPlaybackSpeed",null);class nw extends ew{get __className__(){return "MixingAudioTrack";}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return !0;return !1;}constructor(){const e=mb().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,nS(8,"track-mix-")),sh(this,"trackList",void 0),sh(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack();}catch(e){}this.destNode=e,this.trackList=[];}hasAudioTrack(e){return -1!==this.trackList.indexOf(e);}addAudioTrack(e){-1===this.trackList.indexOf(e)?(jC.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):jC.debug("track ".concat(e.getTrackId()," is already added"));}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){jC.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode);}catch(e){}WT(this.trackList,e),this.updateEncoderConfig();}}updateEncoderConfig(){const e={};this.trackList.forEach(t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0));}),this._encoderConfig=e;}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach(t=>{t instanceof nw?t.emit(KA.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e);}));}}function rw(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=LA(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!Bg()&&i.frameRate&&(t.frameRate=i.frameRate),Sg().name===Eg.EDGE&&"object"==typeof t.frameRate&&(t.frameRate.max=60),wg()&&(t.frameRate={ideal:30,max:30}),t;}function sw(e){const t={};if(Bg()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Ag()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=xA(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize;}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Gg()&&(t.sampleRate=void 0),t;}class ow extends Rb{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(zA.AUDIO_SOURCE_STATE_CHANGE,this._currentState));}get currentState(){return this._currentState;}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),sh(this,"audioBuffer",void 0),sh(this,"sourceNode",void 0),sh(this,"startPlayTime",0),sh(this,"startPlayOffset",0),sh(this,"pausePlayTime",0),sh(this,"options",void 0),sh(this,"currentLoopCount",0),sh(this,"currentPlaybackSpeed",100),sh(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0;}createWebAudioDiagram(){return this.context.createGain();}get duration(){return this.audioBuffer?this.audioBuffer.duration:0;}get playbackSpeed(){return this.currentPlaybackSpeed;}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0;}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):jC.warning("can not set audio source options");}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing";}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused");}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e));}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing");}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop();}catch(e){}this.reset();}}destroy(){this.audioBuffer=null,super.destroy();}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e;}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this));}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e;}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset();}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0;}}const aw=new Map();async function cw(e,t){let i=null;if("string"==typeof e){const t=aw.get(e);if(t)return jC.debug("use cached audio resource: ",e),t;try{i=(await fS(()=>sC.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data;}catch(e){throw new Kg(Hg.FETCH_AUDIO_FILE_FAILED,e.toString());}}else {const t=new cg((t,i)=>{const n=new FileReader();n.onload=e=>{e.target?t(e.target.result):i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR));},n.onerror=()=>{i(new Kg(Hg.READ_LOCAL_AUDIO_FILE_ERROR));},n.readAsArrayBuffer(e);});i=await t;}const n=await function(e){const t=mb();return new cg((i,n)=>{t.decodeAudioData(e,e=>{i(e);},e=>{n(new Kg(Hg.DECODE_AUDIO_FILE_FAILED,e.toString()));});});}(i);return "string"==typeof e&&t&&aw.set(e,n),n;}const dw=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new cg((i,n)=>{t.toBlob(async e=>{if(t.remove(),e){const n=await lw(e);i({buffer:n,width:t.width,height:t.height});}else n(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED));},e,1);});},lw=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t);};function uw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function hw(e){for(var t=1;t ").concat(e)),this._videoElementStatus=e);}get videoState(){return this._videoState;}set videoState(e){var t;e!==this._videoState&&(jC.debug("[".concat(this.trackId,"] video-status change ").concat(this._videoState," => ").concat(e)),this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState));}constructor(e){sh(this,"trackId",void 0),sh(this,"config",void 0),sh(this,"onFirstVideoFrameDecoded",void 0),sh(this,"onVideoStateChanged",void 0),sh(this,"freezeTimeCounterList",[]),sh(this,"renderFreezeAccTime",0),sh(this,"isKeepLastFrame",!1),sh(this,"timeUpdatedCount",0),sh(this,"freezeTime",0),sh(this,"playbackTime",0),sh(this,"lastTimeUpdatedTime",0),sh(this,"autoplayFailed",!1),sh(this,"videoTrack",void 0),sh(this,"videoElement",void 0),sh(this,"cacheVideoElement",void 0),sh(this,"_videoState",ob.VideoStateStopped),sh(this,"videoElementCheckInterval",void 0),sh(this,"videoElementFreezeTimeout",void 0),sh(this,"_videoElementStatus",sb.NONE),sh(this,"isGettingVideoDimensions",!1),sh(this,"startGetVideoDimensions",()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return jC.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500);};!this.isGettingVideoDimensions&&e();}),sh(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===_b.curState&&(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()));}),sh(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=sb.PLAYING;break;case"loadeddata":if(this.videoState=ob.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove();}catch(e){}this.cacheVideoElement=void 0;}break;case"canplay":this.videoElementStatus=sb.CANPLAY;break;case"stalled":this.videoElementStatus=sb.STALLED;break;case"suspend":this.videoElementStatus=sb.SUSPEND;break;case"pause":this.videoElementStatus=sb.PAUSED,Og()||Vg()||bg()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=sb.WAITING;break;case"abort":this.videoElementStatus=sb.ABORT;break;case"ended":this.videoElementStatus=sb.ENDED;break;case"emptied":this.videoElementStatus=sb.EMPTIED;break;case"error":{this.videoElementStatus=sb.ERROR;const e=this.videoElement.error;e&&jC.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break;}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,Dw.lastVisibleTimeRC("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3);}break;}}}),sh(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(jC.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Cg())),xg()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()));}),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),_b.on(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16);}getVideoElement(){return this.videoElement;}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0;}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement();}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement());}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch(t=>{e&&Bb(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(jC.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):jC.warning("[".concat(this.trackId,"] play warning: "),t);});const i=Sg();if(("Safari"===i.name&&15===Number(i.version)||Mg())&&t&&t.then){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)");};t.then(e).catch(e);}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return jC.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const i=t.getImageData(0,0,e.width,e.height);return e.remove(),i;}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new cg((n,r)=>{i.toBlob(async e=>{if(i.remove(),e){const t=await lw(e);n({buffer:t,width:i.width,height:i.height});}else r(new Kg(Hg.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED));},e,t<0?.1:t>1?1:t);})):await dw(e);}destroy(){_b.off(vA.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=ob.VideoStateStopped;}initVideoElement(){if(this.videoElementStatus=sb.INIT,!this.videoElementCheckInterval&&(_w.forEach(e=>{this.videoElement.addEventListener(e,this.handleVideoEvents);}),this.videoElementCheckInterval=window.setInterval(()=>{(function(e){return e!==document.body&&document.body.contains(e);})(this.videoElement)||(this.videoElementStatus=sb.DESTROYED);},1e3),RC("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",n),this.videoElementFreezeTimeout=window.setTimeout(r,RC("VIDEO_FREEZE_DURATION")));},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===ob.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=ob.VideoStateFrozen:document.addEventListener("visibilitychange",n));},s=(e,t)=>{if(this.videoElementStatus===sb.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;this.videoState===ob.VideoStateStarting&&(this.videoState=ob.VideoStateDecoding),this.videoState===ob.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,RC("VIDEO_FREEZE_DURATION"))),eRC("VIDEO_FREEZE_DURATION")&&Dw.lastVisibleTime>=Dw.lastHiddenTime&&i.timestamp>Dw.lastVisibleTime&&i.timestamp>Dw.lastHiddenTime&&(this.renderFreezeAccTime+=e);}i=hw(hw({},t),{},{timestamp:e});}var n,o;RC("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(n=(o=this.videoElement).requestVideoFrameCallback)||void 0===n||n.call(o,s));};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,s);}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Gg()&&(this.videoElement.poster="noposter");const i=Sg();if("Safari"===i.name&&15===Number(i.version)||Mg()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream){this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load());}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,wg()&&this.videoElement.load();const n=this.videoElement.play();void 0!==n&&n.catch(e=>{jC.debug("[".concat(this.trackId,"] playback interrupted"),e.toString());});}resetVideoElement(){_w.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents);}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=sb.NONE;}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{jC.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."));}).catch(e=>{jC.error(e);}),this.autoplayFailed=!1,Wg()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0));};Wg()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),xb();}}const _w=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class Ew extends pw{constructor(e){super(e),sh(this,"container",void 0),sh(this,"slot",void 0),this.slot=e.element,this.updateConfig(e);}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),this.createElements();}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements());}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e);}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2);}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await dw(e);}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container);}catch(e){}this.container=void 0;}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",RC("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container);}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0";}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement);}catch(e){}this.videoElement=document.createElement("video");}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"));}getContainerElement(){return this.container;}}function mw(e){return new cg((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const s=Og()?"canplay":"playing";r.addEventListener(s,()=>{const e=r.videoWidth,i=r.videoHeight;!e&&wg()||(n=!0,r.srcObject=null,r.remove(),t([e,i]));}),r.srcObject=new MediaStream([e]),r.play().catch(sS),setTimeout(()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]));},4e3);});}const fw=async(e,t,i)=>{const n=function(e){const t=[];for(let i=0;i>8*i+4&15)+t.charAt(e>>8*i&15);return n;}function n(e,t){const i=(65535&e)+(65535&t);return (e>>16)+(t>>16)+(i>>16)<<16|65535&i;}function r(e,t,i,r,s,o){return n(function(e,t){return e<>>32-t;}(n(n(t,e),n(r,o)),s),i);}function s(e,t,i,n,s,o,a){return r(t&i|~t&n,e,t,s,o,a);}function o(e,t,i,n,s,o,a){return r(t&n|i&~n,e,t,s,o,a);}function a(e,t,i,n,s,o,a){return r(t^i^n,e,t,s,o,a);}function c(e,t,i,n,s,o,a){return r(i^(t|~n),e,t,s,o,a);}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t>2]|=e.charCodeAt(t)<>2]|=128<await fw(e.buffer,t,i);function Tw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Sw(e){for(var t=1;tthis._previousVideoVisibleStatus=void 0),sh(this,"_encoderConfig",void 0),sh(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),sh(this,"_optimizationMode",void 0),sh(this,"_videoHeight",void 0),sh(this,"_videoWidth",void 0),sh(this,"_forceBitrateLimit",void 0),sh(this,"_enabled",!0),sh(this,"processorDestination",void 0),sh(this,"_processorContext",void 0),bg()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i;}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=t,this._scalabilityMode=i,this._optimizationMode=n,this._hints=s||[],-1===this._hints.indexOf(jA.SCREEN_TRACK))this.updateBitrateFromProfile();else if(function(e,t,i){const n=Sg();return !(n.name!==e||!n.osVersion)&&(i?Number(n.version)>=t&&Number(n.version)<=i:Number(n.version)===t);}(Eg.CHROME,115)&&-1!==Rg().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&IA().supportWebRTCInsertableStream){const i=new MediaStreamTrackProcessor(e),n=new MediaStreamTrackGenerator({kind:"video"});let r,s,o=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),s=void 0,n.removeEventListener("ended",a);};let c=window.setInterval(()=>{if(s&&r&&Date.now()-o>(null!=t?t:1e3))try{"live"===n.readyState?s.enqueue(r.clone()):a();}catch(e){a();}},null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===n.readyState?(s=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close();}});return n.addEventListener("ended",a),i.readable.pipeThrough(d).pipeTo(n.writable),n;}}(e);t&&(jC.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t);}t&&-1!==this._hints.indexOf(jA.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new qb(this.getTrackId(),"local"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents();}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body);}jC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Sw(Sw(Sw({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(YA.VIDEO_ELEMENT_VISIBLE_STATUS,e);}catch(e){}},RC("CHECK_VIDEO_VISIBLE_INTERVAL"));}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._statsTimer&&(this.isUseScaleResolutionDownBy=!1,window.clearInterval(this._statsTimer),this._statsTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug("[".concat(this.getTrackId(),"] stop video playback")));}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}return t||(this._enabled=!1),void jC.info("[".concat(this.getTrackId(),"] setEnabled to false success"));}this._originMediaStreamTrack.enabled=!0;try{await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0);}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,jC.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await yT(this,BA.NEED_MUTE_TRACK,this):await yT(this,BA.NEED_UNMUTE_TRACK,this));}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if("720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=rw({encoderConfig:e});(bg()||Og()||Vg())&&(t.deviceId=void 0),jC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution();}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t;}}this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}getStats(){JT(()=>{jC.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead");},"localVideoTrackGetStatsWarning");const e=AT(this,BA.GET_STATS);return e||Sw({},QA);}async setBeautyEffect(e){jC.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect");}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2);}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await dw(e);}async setBitrateLimit(e){if(jC.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e){this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[t,i]=e;this._videoHeight=i,this._videoWidth=t;}).catch(sS);}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack);}_getDefaultPlayerConfig(){return {fit:"contain"};}async setSenderConfiguration(e){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");jC.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const{bitrateMax:n,bitrateMin:r}=this._encoderConfig;if(null==r||null==n){const{max:s,min:o}=function(e,t,i,n,r){const s=RC("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===s)return {min:n,max:r};if(void 0===r){var o;const a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===s?4*a:2*a,n=null!==(o=n)&&void 0!==o?o:a;}else {var a;n=null!==(a=n)&&void 0!==a?a:Math.floor(r/10);}return {min:n,max:r};}(e,t,i,r,n);this._encoderConfig.bitrateMin=o,this._encoderConfig.bitrateMax=s,jC.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(s,", brMin: ").concat(o,"]"));}}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason));}return t;}return;}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message);}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e;}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset();}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe();}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,"track-video-cloned-"),r=new Rw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,qT(this._scalabilityMode),this._optimizationMode,n,qT(this._hints));return e&&i&&r.setEncoderConfiguration(i),jC.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r;}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Kg(Hg.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Kg(Hg.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution();}startMonitorStats(){if(!bg()&&!Og())return;this._statsTimer&&window.clearInterval(this._statsTimer);let e=2,t=NA[e];let i=-1;let n=Date.now();const r=e=>{e>2||e<0||(n=Date.now(),t=NA[e],this.setSenderConfiguration(t));};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval(()=>{const s=this.getStats(),o=AT(this,BA.GET_RTC_STATS);if(s.sendPackets>0&&o){-1===i&&(i=Date.now());const a=Date.now();if(a-i<1e3||a-n0&&c0&&(e--,r(e),jC.debug("[".concat(this.getTrackId(),"] step down for fps ").concat(c,", switchProfile to ").concat(e))):o.OutgoingAvailableBandwidth0&&(e--,r(e),jC.debug("[".concat(this.getTrackId(),"] step down for OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", bitrateMin ").concat(t.bitrateMin,", switchProfile to ").concat(e))):"number"==typeof c&&c>l&&e1.2*NA[e+1].bitrateMin&&(e++,r(e),jC.debug("[".concat(this.getTrackId(),"] step up for fps ").concat(c,", OutgoingAvailableBandwidth ").concat(o.OutgoingAvailableBandwidth,", switchProfile to ").concat(e)));}},RC("CHECK_LOCAL_STATS_INTERVAL"));}sendSeiData(e){if(JT(()=>{eI.reportApiInvoke(null,{name:hT.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:pT.TRACER}).onSuccess("");},this._mediaStreamTrack.id||this.getTrackId()),!RC("ENABLE_VIDEO_SEI")||!RC("ENABLE_ENCODED_TRANSFORM"))return void jC.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==!1)return new Kg(Hg.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void jC.warning("Video track is not published, SEI can not be send");const i=t.sender.getParameters();if(0===i.codecs.length)return;const n=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===n?this.safeEmit("sei-to-send",e):jC.warning("SEI is not supported by ".concat(n));}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await yT(this,BA.NEED_REPLACE_TRACK,this));});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK);}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(ib.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(ib.REQUEST_CONSTRAINTS);}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",void 0)],Rw.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"stop",null),DI([_S("LocalVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean]),PI("design:returntype",cg)],Rw.prototype,"setEnabled",null),DI([_S("LocalVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],Rw.prototype,"setMuted",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],Rw.prototype,"setEncoderConfiguration",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Object)],Rw.prototype,"getStats",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object]),PI("design:returntype",cg)],Rw.prototype,"setBeautyEffect",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",ImageData)],Rw.prototype,"getCurrentFrameData",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[String,Number]),PI("design:returntype",cg)],Rw.prototype,"getCurrentFrameImage",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Rw.prototype,"setBitrateLimit",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],Rw.prototype,"setOptimizationMode",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],Rw.prototype,"setScalabiltyMode",null),DI([Wb(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"updateMediaStreamTrackResolution",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Rw.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"unpipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"close",null),DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),PI("design:type",Function),PI("design:paramtypes",[MediaStreamTrack,Boolean]),PI("design:returntype",cg)],Rw.prototype,"replaceTrack",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Rw.prototype,"startMonitorStats",null);class Cw extends Rw{get __className__(){return "CameraVideoTrack";}constructor(e,t,i,n,r,s){super(e,LA(t.encoderConfig),n,r,s),sh(this,"_config",void 0),sh(this,"_originalConstraints",void 0),sh(this,"_constraints",void 0),sh(this,"_enabled",!0),sh(this,"_deviceName","default"),sh(this,"tryResumeVideoForIOS15_16WeChat",async()=>{(Mg()||Ug())&&!function(){const e=Sg();if(e.os!==_g.IOS||!e.osVersion)return !1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2;}()&&Fg()&&this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack());}),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=LA(this._config.encoderConfig),_b.on(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.on(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents();}async setDevice(e){return "string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0;}async _setDeviceById(e){if(jC.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await kb.getDeviceById(e),i={};i.video=Sw({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Nb(i,this.getTrackId());}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e;}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}else try{const t=await kb.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e};}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setDevice success"));}async _setDeviceByFacingModel(e){jC.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Sw(Sw({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await Nb(t,this.getTrackId());}catch(t){throw jC.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await Nb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t;}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution();}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Sw({},t.video),jC.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"));}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e);}if(jC.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else {const e=await Nb({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1);}await yT(this,BA.NEED_ENABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e;}this.updateMediaStreamTrackResolution(),jC.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0);}else {this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await yT(this,BA.NEED_DISABLE_TRACK,this);}catch(e){throw jC.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e;}jC.info("[".concat(this.getTrackId(),"] setEnabled to false success"));}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Kg(Hg.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");"720p_auto"===e?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),e=LA(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin);const i=YT(this._config);i.encoderConfig=e;const n=rw(i);(bg()||Og()||Vg())&&(n.deviceId=void 0),jC.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution();}catch(e){const t=new Kg(Hg.UNEXPECTED_ERROR,e.toString());throw jC.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t;}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(jA.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await yT(this,BA.NEED_UPDATE_VIDEO_ENCODER,this);}catch(e){return e.throw(jC);}}_getDefaultPlayerConfig(){return {mirror:!0,fit:"cover"};}onTrackEnded(){if((Og()||Vg())&&this._enabled&&!this._isClosed&&_b.duringInterruption){const e=async()=>{_b.off(vA.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(jC.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0));};_b.on(vA.IOS_INTERRUPTION_END,e);}else jC.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(YA.TRACK_ENDED);}async renewMediaStreamTrack(e){const t=e||this._constraints,i=kb.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Nb({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution();}}close(){super.close(),_b.off(vA.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),_b.off(vA.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat);}clone(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;e&&(i=Sw(Sw({},i),LA(e))),i=qT(i);const n=nS(8,"track-cam-cloned-"),r=new Cw(t?this._mediaStreamTrack.clone():this._mediaStreamTrack,qT(Sw(Sw({},this._config),{},{encoderConfig:i})),qT(this._constraints),qT(this._scalabilityMode),this._optimizationMode,n);return e&&i&&r.setEncoderConfiguration(i),jC.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(t)),r;}bindProcessorContextEvents(){this.processorContext.on(ib.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t();}catch(e){i(e);}}),this.processorContext.on(ib.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings());});}}function Iw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function vw(e){for(var t=1;t[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Cw.prototype,"setDevice",null),DI([_S("CameraVideoTrack","_enabledMutex"),$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Boolean]),PI("design:returntype",cg)],Cw.prototype,"setEnabled",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),Wb(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],Cw.prototype,"setEncoderConfiguration",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Cw.prototype,"close",null);class ww extends db{getUserId(){return this._userId;}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(nS(5,""))),sh(this,"_userId",void 0),sh(this,"_uintId",void 0),sh(this,"_isDestroyed",!1),sh(this,"store",void 0),sh(this,"processor",void 0),this._userId=t,this._uintId=i,this.store=n;}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext});}_destroy(){this._isDestroyed=!0,jC.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close();}getProcessorStats(){return this.processorContext.gatherStats();}getProcessorUsage(){return this.processorContext.gatherUsage();}}class Ow extends ww{get isPlaying(){return !(!this._player||this._player.videoElementStatus!==sb.PLAYING);}get __className__(){return "RemoteVideoTrack";}constructor(e,t,i,n){super(e,t,i,n),sh(this,"_videoVisibleTimer",null),sh(this,"_previousVideoVisibleStatus",void 0),sh(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),sh(this,"trackMediaType","video"),sh(this,"_videoWidth",void 0),sh(this,"_videoHeight",void 0),sh(this,"_player",void 0),sh(this,"processorDestination",void 0),sh(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new qb(this.getTrackId(),"remote"),this.processorDestination=new Yb(this.processorContext),this.bindProcessorDestinationEvents();}getStats(){JT(()=>{jC.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead");},"remoteVideoTrackGetStatsWarning");return AT(this,BA.GET_STATS)||bw({},eb);}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(jC.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body);}jC.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=bw(bw({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new pw(i):this._player=new Ew(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(qA.FIRST_FRAME_DECODED);},this._player.onVideoStateChanged=e=>{this.safeEmit(qA.VIDEO_STATE_CHANGED,e);}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(qA.VIDEO_ELEMENT_VISIBLE_STATUS,e);}catch(e){}},RC("CHECK_VIDEO_VISIBLE_INTERVAL"));}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,jC.debug("[".concat(this.getTrackId(),"] stop video playback")));}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2);}updateMediaStreamTrackResolution(){mw(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t;}).catch(sS);}_updatePlayerSource(){jC.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack);}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:s}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&s instanceof HTMLElement){const e=rT.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason));}return t;}return;}catch(e){throw new Kg(Hg.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message);}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e;}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset();}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource());});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK);}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents();}_onSei(e){this.emit(KA.SEI_RECEIVED,e);}}DI([$C({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",void 0)],Ow.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Ow.prototype,"stop",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Ow.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Ow.prototype,"unpipe",null);class Nw extends ww{get isPlaying(){return this._useAudioElement?Gb.isPlaying(this.getTrackId()):this._source.isPlayed;}get __className__(){return "RemoteAudioTrack";}constructor(e,t,i,n){super(e,t,i,n),sh(this,"trackMediaType","audio"),sh(this,"_source",void 0),sh(this,"_useAudioElement",!0),sh(this,"_volume",100),sh(this,"processorContext",void 0),sh(this,"processorDestination",void 0),sh(this,"_played",!1),sh(this,"_bypassWebAudio",!1),RC("DISABLE_WEBAUDIO")?(this._source=new Xb(),this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Cb(e,!0),RC("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(zA.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(qA.FIRST_FRAME_DECODED);}),this.processorContext=new Jb(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new zb(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(zA.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext});});}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(zA.ON_AUDIO_BUFFER),this._source.on(zA.ON_AUDIO_BUFFER,t=>e(t));}setVolume(e){this._volume=e,this._useAudioElement?Gb.setVolume(this.getTrackId(),e):this._source.setVolume(e/100);}async setPlaybackDevice(e){if(!this._useAudioElement||!Ag()&&RC("RESTRICTION_SET_PLAYBACK_DEVICE"))throw new Kg(Hg.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Gb.setSinkID(this.getTrackId(),e);}getVolumeLevel(){return this._source.getAccurateVolumeLevel();}getStats(){JT(()=>{jC.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead");},"remoteAudioTrackGetStatsWarning");return AT(this,BA.GET_STATS)||bw({},ZA);}play(){jC.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(jC.debug("[".concat(this.getTrackId(),"] use audio element to play")),Gb.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play();}stop(){jC.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Gb.stop(this.getTrackId()):this._source.stop();}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy();}_isFreeze(){return this._source.isFreeze;}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];jC.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Gb.updateTrack(this.getTrackId(),this._mediaStreamTrack);}pipe(e){if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Kg(Hg.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e;}unpipe(){var e;if(this._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset();}bindProcessorDestinationEvents(){this.processorDestination.on(tb.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource());}),this.processorDestination.on(tb.ON_NODE,e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t);});}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(tb.ON_TRACK),this.processorDestination.removeAllListeners(tb.ON_NODE);}}DI([$C({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],Nw.prototype,"setVolume",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t]}),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],Nw.prototype,"setPlaybackDevice",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"play",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"stop",null),DI([$C({argsMap:(e,t)=>[e.getTrackId(),t.name]}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",Object)],Nw.prototype,"pipe",null),DI([$C({argsMap:e=>[e.getTrackId()]}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Nw.prototype,"unpipe",null);const Dw=new class extends dT{get visibility(){return document.visibilityState;}get lastHiddenTime(){return this._lastHiddenTime;}get lastVisibleTime(){return this._lastVisibleTime;}constructor(){super(),sh(this,"_lastHiddenTime",0),sh(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),jC.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState);});}}();/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */function Pw(e){let t=e.length;for(;--t>=0;)e[t]=0;}const Lw=256,kw=286,Mw=30,Uw=15,xw=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Vw=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Fw=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Bw=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jw=new Array(576);Pw(jw);const Gw=new Array(60);Pw(Gw);const Ww=new Array(512);Pw(Ww);const Hw=new Array(256);Pw(Hw);const Kw=new Array(29);Pw(Kw);const Yw=new Array(Mw);function qw(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length;}let zw,Jw,Xw;function Qw(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t;}Pw(Yw);const Zw=e=>e<256?Ww[e]:Ww[256+(e>>>7)],$w=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255;},eO=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{eO(e,i[2*t],i[2*t+1]);},iO=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1;}while(--t>0);return i>>>1;},nO=(e,t,i)=>{const n=new Array(16);let r,s,o=0;for(r=1;r<=Uw;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=iO(n[t]++,t));}},rO=e=>{let t;for(t=0;t{e.bi_valid>8?$w(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0;},oO=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r{let n,r,s,o,a=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+a++],n+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===n?tO(e,r,t):(s=Hw[r],tO(e,s+Lw+1,t),o=xw[s],0!==o&&(r-=Kw[s],eO(e,r,o)),n--,s=Zw(n),tO(e,s,i),o=Vw[s],0!==o&&(n-=Yw[s],eO(e,n,o)));}while(a{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let o,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,o=0;o>1;o>=1;o--)aO(e,i,o);c=s;do{o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],aO(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=a,i[2*c]=i[2*o]+i[2*a],e.depth[c]=(e.depth[o]>=e.depth[a]?e.depth[o]:e.depth[a])+1,i[2*o+1]=i[2*a+1]=c,e.heap[1]=c++,aO(e,i,1);}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=Uw;h++)e.bl_count[h]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=i[2*i[2*l+1]+1]+1,h>c&&(h=c,E++),i[2*l+1]=h,l>n||(e.bl_count[h]++,p=0,l>=a&&(p=o[l-a]),_=i[2*l],e.opt_len+=_*(h+p),s&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2;}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>n||(i[2*u+1]!==h&&(e.opt_len+=(h-i[2*u+1])*i[2*u],i[2*u+1]=h),l--);}})(e,t),nO(i,d,e.bl_count);},lO=(e,t,i)=>{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=o,o=t[2*(n+1)+1],++a{let n,r,s=-1,o=t[1],a=0,c=7,d=4;for(0===o&&(c=138,d=3),n=0;n<=i;n++)if(r=o,o=t[2*(n+1)+1],!(++a{eO(e,0+(n?1:0),3),sO(e),$w(e,i),$w(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i;};var _O=e=>{hO||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(Kw[n]=i,e=0;e<1<>=7;n{let r,s,o=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t{let t;for(lO(e,e.dyn_ltree,e.l_desc.max_code),lO(e,e.dyn_dtree,e.d_desc.max_code),dO(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Bw[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t;})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?pO(e,t,i,n):4===e.strategy||s===r?(eO(e,2+(n?1:0),3),cO(e,jw,Gw)):(eO(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(eO(e,t-257,5),eO(e,i-1,5),eO(e,n-4,4),r=0;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Hw[i]+Lw+1)]++,e.dyn_dtree[2*Zw(t)]++),e.sym_next===e.sym_end),fO={_tr_init:_O,_tr_stored_block:pO,_tr_flush_block:EO,_tr_tally:mO,_tr_align:e=>{eO(e,2,3),tO(e,256,jw),(e=>{16===e.bi_valid?($w(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8);})(e);}};var gO=(e,t,i,n)=>{let r=65535&e|0,s=e>>>16&65535|0,o=0;for(;0!==i;){o=i>2e3?2e3:i,i-=o;do{r=r+t[n++]|0,s=s+r|0;}while(--o);r%=65521,s%=65521;}return r|s<<16|0;};const TO=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e;}return t;})());var SO=(e,t,i,n)=>{const r=TO,s=n+i;e^=-1;for(let i=n;i>>8^r[255&(e^t[i])];return -1^e;},RO={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},CO={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:IO,_tr_stored_block:vO,_tr_flush_block:yO,_tr_tally:AO,_tr_align:bO}=fO,{Z_NO_FLUSH:wO,Z_PARTIAL_FLUSH:OO,Z_FULL_FLUSH:NO,Z_FINISH:DO,Z_BLOCK:PO,Z_OK:LO,Z_STREAM_END:kO,Z_STREAM_ERROR:MO,Z_DATA_ERROR:UO,Z_BUF_ERROR:xO,Z_DEFAULT_COMPRESSION:VO,Z_FILTERED:FO,Z_HUFFMAN_ONLY:BO,Z_RLE:jO,Z_FIXED:GO,Z_DEFAULT_STRATEGY:WO,Z_UNKNOWN:HO,Z_DEFLATED:KO}=CO,YO=286,qO=30,zO=19,JO=2*YO+1,XO=15,QO=258,ZO=262,$O=42,eN=113,tN=666,iN=(e,t)=>(e.msg=RO[t],t),nN=e=>2*e-(e>4?9:0),rN=e=>{let t=e.length;for(;--t>=0;)e[t]=0;},sN=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0;}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0;}while(--t);};let oN=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0));},cN=(e,t)=>{yO(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,aN(e.strm);},dN=(e,t)=>{e.pending_buf[e.pending++]=t;},lN=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t;},uN=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=gO(e.adler,t,r,i):2===e.state.wrap&&(e.adler=SO(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r);},hN=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,o=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-ZO?e.strstart-(e.w_size-ZO):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+QO;let p=d[s+o-1],_=d[s+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,d[i+o]===_&&d[i+o-1]===p&&d[i]===d[s]&&d[++i]===d[s+1]){s+=2,i++;do{}while(d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&d[++s]===d[++i]&&so){if(e.match_start=t,o=n,n>=a)break;p=d[s+o-1],_=d[s+o];}}}while((t=u[t&l])>c&&0!=--r);return o<=e.lookahead?o:e.lookahead;},pN=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ZO)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),sN(e),n+=t),0===e.strm.avail_in)break;if(i=uN(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=oN(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=oN(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_outn+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,aN(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(uN(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i);}while(0===o);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(uN(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===DO)&&t!==wO&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,o=t===DO&&0===e.strm.avail_in&&i===n?1:0,vO(e,e.block_start,i,o),e.block_start+=i,aN(e.strm)),o?3:1);},EN=(e,t)=>{let i,n;for(;;){if(e.lookahead=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-ZO&&(e.match_length=hN(e,i)),e.match_length>=3){if(n=AO(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;}while(0!=--e.match_length);e.strstart++;}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=oN(e,e.ins_h,e.window[e.strstart+1]);}else n=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;},mN=(e,t)=>{let i,n,r;for(;;){if(e.lookahead=3&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=AO(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=oN(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(cN(e,!1),0===e.strm.avail_out))return 1;}else if(e.match_available){if(n=AO(e,0,e.window[e.strstart-1]),n&&cN(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1;}else e.match_available=1,e.strstart++,e.lookahead--;}return e.match_available&&(n=AO(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;};function fN(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r;}const gN=[new fN(0,0,0,0,_N),new fN(4,4,8,4,EN),new fN(4,5,16,8,EN),new fN(4,6,32,32,EN),new fN(4,4,16,16,mN),new fN(8,16,32,32,mN),new fN(8,16,128,128,mN),new fN(8,32,128,256,mN),new fN(32,128,258,1024,mN),new fN(32,258,258,4096,mN)];function TN(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=KO,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*JO),this.dyn_dtree=new Uint16Array(2*(2*qO+1)),this.bl_tree=new Uint16Array(2*(2*zO+1)),rN(this.dyn_ltree),rN(this.dyn_dtree),rN(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(XO+1),this.heap=new Uint16Array(2*YO+1),rN(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*YO+1),rN(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}const SN=e=>{if(!e)return 1;const t=e.state;return !t||t.strm!==e||t.status!==$O&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==eN&&t.status!==tN?1:0;},RN=e=>{if(SN(e))return iN(e,MO);e.total_in=e.total_out=0,e.data_type=HO;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?$O:eN,e.adler=2===t.wrap?0:1,t.last_flush=-2,IO(t),LO;},CN=e=>{const t=RN(e);var i;return t===LO&&((i=e.state).window_size=2*i.w_size,rN(i.head),i.max_lazy_match=gN[i.level].max_lazy,i.good_match=gN[i.level].good_length,i.nice_match=gN[i.level].nice_length,i.max_chain_length=gN[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t;},IN=(e,t,i,n,r,s)=>{if(!e)return MO;let o=1;if(t===VO&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||i!==KO||n<8||n>15||t<0||t>9||s<0||s>GO||8===n&&1!==o)return iN(e,MO);8===n&&(n=9);const a=new TN();return e.state=a,a.strm=e,a.status=$O,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<{if(SN(e)||t>PO||t<0)return e?iN(e,MO):MO;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===tN&&t!==DO)return iN(e,0===e.avail_out?xO:MO);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(aN(e),0===e.avail_out)return i.last_flush=-1,LO;}else if(0===e.avail_in&&nN(t)<=nN(n)&&t!==DO)return iN(e,xO);if(i.status===tN&&0!==e.avail_in)return iN(e,xO);if(i.status===$O&&0===i.wrap&&(i.status=eN),i.status===$O){let t=KO+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=BO||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,lN(i,t),0!==i.strstart&&(lN(i,e.adler>>>16),lN(i,65535&e.adler)),e.adler=1,i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;}if(57===i.status)if(e.adler=0,dN(i,31),dN(i,139),dN(i,8),i.gzhead)dN(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),dN(i,255&i.gzhead.time),dN(i,i.gzhead.time>>8&255),dN(i,i.gzhead.time>>16&255),dN(i,i.gzhead.time>>24&255),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(dN(i,255&i.gzhead.extra.length),dN(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=SO(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,0),dN(i,9===i.level?2:i.strategy>=BO||i.level<2?4:0),dN(i,3),i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,aN(e),0!==i.pending)return i.last_flush=-1,LO;t=0,n-=r;}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=SO(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0;}i.status=73;}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0;}t=i.gzindexn&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0;}i.status=91;}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n)),aN(e),0!==i.pending)return i.last_flush=-1,LO;n=0;}t=i.gzindexn&&(e.adler=SO(e.adler,i.pending_buf,i.pending-n,n));}i.status=103;}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(aN(e),0!==i.pending))return i.last_flush=-1,LO;dN(i,255&e.adler),dN(i,e.adler>>8&255),e.adler=0;}if(i.status=eN,aN(e),0!==i.pending)return i.last_flush=-1,LO;}if(0!==e.avail_in||0!==i.lookahead||t!==wO&&i.status!==tN){let n=0===i.level?_N(i,t):i.strategy===BO?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(pN(e),0===e.lookahead)){if(t===wO)return 1;break;}if(e.match_length=0,i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;})(i,t):i.strategy===jO?((e,t)=>{let i,n,r,s;const o=e.window;for(;;){if(e.lookahead<=QO){if(pN(e),e.lookahead<=QO&&t===wO)return 1;if(0===e.lookahead)break;}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=o[r],n===o[++r]&&n===o[++r]&&n===o[++r])){s=e.strstart+QO;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&re.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=3?(i=AO(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=AO(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(cN(e,!1),0===e.strm.avail_out))return 1;}return e.insert=0,t===DO?(cN(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(cN(e,!1),0===e.strm.avail_out)?1:2;})(i,t):gN[i.level].func(i,t);if(3!==n&&4!==n||(i.status=tN),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),LO;if(2===n&&(t===OO?bO(i):t!==PO&&(vO(i,0,0,!1),t===NO&&(rN(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),aN(e),0===e.avail_out))return i.last_flush=-1,LO;}return t!==DO?LO:i.wrap<=0?kO:(2===i.wrap?(dN(i,255&e.adler),dN(i,e.adler>>8&255),dN(i,e.adler>>16&255),dN(i,e.adler>>24&255),dN(i,255&e.total_in),dN(i,e.total_in>>8&255),dN(i,e.total_in>>16&255),dN(i,e.total_in>>24&255)):(lN(i,e.adler>>>16),lN(i,65535&e.adler)),aN(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?LO:kO);},yN=(e,t)=>{let i=t.length;if(SN(e))return MO;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==$O||n.lookahead)return MO;if(1===r&&(e.adler=gO(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(rN(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size;}const s=e.avail_in,o=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,pN(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=oN(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++;}while(--t);n.strstart=e,n.lookahead=2,pN(n);}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=o,e.input=a,e.avail_in=s,n.wrap=r,LO;},AN={deflateInit:(e,t)=>IN(e,t,KO,15,8,WO),deflateInit2:IN,deflateReset:CN,deflateResetKeep:RN,deflateSetHeader:(e,t)=>SN(e)||2!==e.state.wrap?MO:(e.state.gzhead=t,LO),deflate:vN,deflateEnd:e=>{if(SN(e))return MO;const t=e.state.status;return e.state=null,t===eN?iN(e,UO):LO;},deflateSetDictionary:yN,deflateInfo:"pako deflate (from Nodeca project)"};const bN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var wN={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)bN(i,t)&&(e[t]=i[t]);}}return e;},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;NN[254]=NN[254]=1;var DN={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let t,i,n,r,s,o=e.length,a=0;for(r=0;r>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t;},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n4)s[r++]=65533,n+=o-1;else {for(t&=2===o?31:3===o?15:7;o>1&&n1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t);}}return ((e,t)=>{if(t<65534&&e.subarray&&ON)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+NN[e[i]]>t?i:t;}};var PN=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;};const LN=Object.prototype.toString,{Z_NO_FLUSH:kN,Z_SYNC_FLUSH:MN,Z_FULL_FLUSH:UN,Z_FINISH:xN,Z_OK:VN,Z_STREAM_END:FN,Z_DEFAULT_COMPRESSION:BN,Z_DEFAULT_STRATEGY:jN,Z_DEFLATED:GN}=CO;function WN(e){this.options=wN.assign({level:BN,method:GN,chunkSize:16384,windowBits:15,memLevel:8,strategy:jN},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new PN(),this.strm.avail_out=0;let i=AN.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==VN)throw new Error(RO[i]);if(t.header&&AN.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?DN.string2buf(t.dictionary):"[object ArrayBuffer]"===LN.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=AN.deflateSetDictionary(this.strm,e),i!==VN)throw new Error(RO[i]);this._dict_set=!0;}}function HN(e,t){const i=new WN(t);if(i.push(e,!0),i.err)throw i.msg||RO[i.err];return i.result;}WN.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return !1;for(s=t===~~t?t:!0===t?xN:kN,"string"==typeof e?i.input=DN.string2buf(e):"[object ArrayBuffer]"===LN.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===MN||s===UN)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else {if(r=AN.deflate(i,s),r===FN)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=AN.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===VN;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break;}else this.onData(i.output);}return !0;},WN.prototype.onData=function(e){this.chunks.push(e);},WN.prototype.onEnd=function(e){e===VN&&(this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};var KN={Deflate:WN,deflate:HN,deflateRaw:function(e,t){return (t=t||{}).raw=!0,HN(e,t);},gzip:function(e,t){return (t=t||{}).gzip=!0,HN(e,t);},constants:CO};const YN=16209;var qN=function(e,t){let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v,y;const A=e.state;i=e.next_in,v=e.input,n=i+(e.avail_in-5),r=e.next_out,y=e.output,s=r-(t-e.avail_out),o=r+(e.avail_out-257),a=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,u=A.window,h=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<>>24,h>>>=T,p-=T,T=g>>>16&255,0===T)y[r++]=65535&g;else {if(!(16&T)){if(0==(64&T)){g=_[(65535&g)+(h&(1<>>=T,p-=T),p<15&&(h+=v[i++]<>>24,h>>>=T,p-=T,T=g>>>16&255,!(16&T)){if(0==(64&T)){g=E[(65535&g)+(h&(1<a){e.msg="invalid distance too far back",A.mode=YN;break e;}if(h>>>=T,p-=T,T=r-s,R>T){if(T=R-T,T>d&&A.sane){e.msg="invalid distance too far back",A.mode=YN;break e;}if(C=0,I=u,0===l){if(C+=c-T,T2;)y[r++]=I[C++],y[r++]=I[C++],y[r++]=I[C++],S-=3;S&&(y[r++]=I[C++],S>1&&(y[r++]=I[C++]));}else {C=r-R;do{y[r++]=y[C++],y[r++]=y[C++],y[r++]=y[C++],S-=3;}while(S>2);S&&(y[r++]=y[C++],S>1&&(y[r++]=y[C++]));}break;}}break;}}while(i>3,i-=S,p-=S<<3,h&=(1<{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,T=0,S=0,R=0,C=0,I=0,v=0,y=null;const A=new Uint16Array(16),b=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=zN;E++)A[E]=0;for(m=0;m=1&&0===A[g];g--);if(T>g&&(T=g),0===g)return r[s++]=20971520,r[s++]=20971520,a.bits=1,0;for(f=1;f0&&(0===e||1!==g))return -1;for(b[1]=0,E=1;E852||2===e&&I>592)return 1;for(;;){w=E-R,o[m]+1<_?(O=0,N=o[m]):o[m]>=_?(O=D[o[m]-_],N=y[o[m]-_]):(O=96,N=0),d=1<>R)+l]=w<<24|O<<16|N|0;}while(0!==l);for(d=1<>=1;if(0!==d?(v&=d-1,v+=d):v=0,m++,0==--A[E]){if(E===g)break;E=t[i+o[m]];}if(E>T&&(v&h)!==u){for(0===R&&(R=T),p+=f,S=E-R,C=1<852||2===e&&I>592)return 1;u=v&h,r[u]=T<<24|S<<16|p-s|0;}}return 0!==v&&(r[p+v]=E-R<<24|64<<16|0),a.bits=T,0;};const{Z_FINISH:eD,Z_BLOCK:tD,Z_TREES:iD,Z_OK:nD,Z_STREAM_END:rD,Z_NEED_DICT:sD,Z_STREAM_ERROR:oD,Z_DATA_ERROR:aD,Z_MEM_ERROR:cD,Z_BUF_ERROR:dD,Z_DEFLATED:lD}=CO,uD=16180,hD=16190,pD=16191,_D=16192,ED=16194,mD=16199,fD=16200,gD=16206,TD=16209,SD=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function RD(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}const CD=e=>{if(!e)return 1;const t=e.state;return !t||t.strm!==e||t.mode16211?1:0;},ID=e=>{if(CD(e))return oD;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=uD,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,nD;},vD=e=>{if(CD(e))return oD;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,ID(e);},yD=(e,t)=>{let i;if(CD(e))return oD;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?oD:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,vD(e));},AD=(e,t)=>{if(!e)return oD;const i=new RD();e.state=i,i.strm=e,i.window=null,i.mode=uD;const n=yD(e,t);return n!==nD&&(e.state=null),n;};let bD,wD,OD=!0;const ND=e=>{if(OD){bD=new Int32Array(512),wD=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for($N(1,e.lens,0,288,bD,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;$N(2,e.lens,0,32,wD,0,e.work,{bits:5}),OD=!1;}e.lencode=bD,e.lenbits=9,e.distcode=wD,e.distbits=5;},DD=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave{let i,n,r,s,o,a,c,d,l,u,h,p,_,E,m,f,g,T,S,R,C,I,v=0;const y=new Uint8Array(4);let A,b;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(CD(e)||!e.output||!e.input&&0!==e.avail_in)return oD;i=e.state,i.mode===pD&&(i.mode=_D),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,u=a,h=c,I=nD;e:for(;;)switch(i.mode){case uD:if(0===i.wrap){i.mode=_D;break;}for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(i.check,y,2,0),d=0,l=0,i.mode=16181;break;}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",i.mode=TD;break;}if((15&d)!==lD){e.msg="unknown compression method",i.mode=TD;break;}if(d>>>=4,l-=4,C=8+(15&d),0===i.wbits&&(i.wbits=C),C>15||C>i.wbits){e.msg="invalid window size",i.mode=TD;break;}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<>>8&255,y[2]=d>>>16&255,y[3]=d>>>24&255,i.check=SO(i.check,y,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>8),512&i.flags&&4&i.wrap&&(y[0]=255&d,y[1]=d>>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&i.flags){for(;l<16;){if(0===a)break e;a--,d+=n[s++]<>>8&255,i.check=SO(i.check,y,2,0)),d=0,l=0;}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(p=i.length,p>a&&(p=a),p&&(i.head&&(C=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+p),C)),512&i.flags&&4&i.wrap&&(i.check=SO(i.check,n,p,s)),a-=p,s+=p,i.length-=p),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;p=0;do{C=n[s+p++],i.head&&C&&i.length<65536&&(i.head.name+=String.fromCharCode(C));}while(C&&p>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=pD;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=n[s++]<>>=7&l,l-=7&l,i.mode=gD;break;}for(;l<3;){if(0===a)break e;a--,d+=n[s++]<>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(ND(i),i.mode=mD,t===iD){d>>>=2,l-=2;break e;}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=TD;}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=TD;break;}if(i.length=65535&d,d=0,l=0,i.mode=ED,t===iD)break e;case ED:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(n.subarray(s,s+p),o),a-=p,s+=p,c-=p,o+=p,i.length-=p;break;}i.mode=pD;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=n[s++]<>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=TD;break;}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,l-=3;}for(;i.have<19;)i.lens[w[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,A={bits:i.lenbits},I=$N(0,i.lens,0,19,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid code lengths set",i.mode=TD;break;}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=m,l-=m,i.lens[i.have++]=g;else {if(16===g){for(b=m+2;l>>=m,l-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=TD;break;}C=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2;}else if(17===g){for(b=m+3;l>>=m,l-=m,C=0,p=3+(7&d),d>>>=3,l-=3;}else {for(b=m+7;l>>=m,l-=m,C=0,p=11+(127&d),d>>>=7,l-=7;}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=TD;break;}for(;p--;)i.lens[i.have++]=C;}}if(i.mode===TD)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=TD;break;}if(i.lenbits=9,A={bits:i.lenbits},I=$N(1,i.lens,0,i.nlen,i.lencode,0,i.work,A),i.lenbits=A.bits,I){e.msg="invalid literal/lengths set",i.mode=TD;break;}if(i.distbits=6,i.distcode=i.distdyn,A={bits:i.distbits},I=$N(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,A),i.distbits=A.bits,I){e.msg="invalid distances set",i.mode=TD;break;}if(i.mode=mD,t===iD)break e;case mD:i.mode=fD;case fD:if(a>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=s,e.avail_in=a,i.hold=d,i.bits=l,qN(e,h),o=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,a=e.avail_in,d=i.hold,l=i.bits,i.mode===pD&&(i.back=-1);break;}for(i.back=0;v=i.lencode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,i.length=g,0===f){i.mode=16205;break;}if(32&f){i.back=-1,i.mode=pD;break;}if(64&f){e.msg="invalid literal/length code",i.mode=TD;break;}i.extra=15&f,i.mode=16201;case 16201:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra;}i.was=i.length,i.mode=16202;case 16202:for(;v=i.distcode[d&(1<>>24,f=v>>>16&255,g=65535&v,!(m<=l);){if(0===a)break e;a--,d+=n[s++]<>T)],m=v>>>24,f=v>>>16&255,g=65535&v,!(T+m<=l);){if(0===a)break e;a--,d+=n[s++]<>>=T,l-=T,i.back+=T;}if(d>>>=m,l-=m,i.back+=m,64&f){e.msg="invalid distance code",i.mode=TD;break;}i.offset=g,i.extra=15&f,i.mode=16203;case 16203:if(i.extra){for(b=i.extra;l>>=i.extra,l-=i.extra,i.back+=i.extra;}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=TD;break;}i.mode=16204;case 16204:if(0===c)break e;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=TD;break;}p>i.wnext?(p-=i.wnext,_=i.wsize-p):_=i.wnext-p,p>i.length&&(p=i.length),E=i.window;}else E=r,_=o-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do{r[o++]=E[_++];}while(--p);0===i.length&&(i.mode=fD);break;case 16205:if(0===c)break e;r[o++]=i.length,c--,i.mode=fD;break;case gD:if(i.wrap){for(;l<32;){if(0===a)break e;a--,d|=n[s++]<AD(e,15),inflateInit2:AD,inflate:PD,inflateEnd:e=>{if(CD(e))return oD;let t=e.state;return t.window&&(t.window=null),e.state=null,nD;},inflateGetHeader:(e,t)=>{if(CD(e))return oD;const i=e.state;return 0==(2&i.wrap)?oD:(i.head=t,t.done=!1,nD);},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return CD(e)?oD:(n=e.state,0!==n.wrap&&n.mode!==hD?oD:n.mode===hD&&(r=1,r=gO(r,t,i,0),r!==n.check)?aD:(s=DD(e,t,i,i),s?(n.mode=16210,cD):(n.havedict=1,nD)));},inflateInfo:"pako inflate (from Nodeca project)"};var kD=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1;};const MD=Object.prototype.toString,{Z_NO_FLUSH:UD,Z_FINISH:xD,Z_OK:VD,Z_STREAM_END:FD,Z_NEED_DICT:BD,Z_STREAM_ERROR:jD,Z_DATA_ERROR:GD,Z_MEM_ERROR:WD}=CO;function HD(e){this.options=wN.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new PN(),this.strm.avail_out=0;let i=LD.inflateInit2(this.strm,t.windowBits);if(i!==VD)throw new Error(RO[i]);if(this.header=new kD(),LD.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=DN.string2buf(t.dictionary):"[object ArrayBuffer]"===MD.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=LD.inflateSetDictionary(this.strm,t.dictionary),i!==VD)))throw new Error(RO[i]);}function KD(e,t){const i=new HD(t);if(i.push(e),i.err)throw i.msg||RO[i.err];return i.result;}HD.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,o,a;if(this.ended)return !1;for(o=t===~~t?t:!0===t?xD:UD,"[object ArrayBuffer]"===MD.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=LD.inflate(i,o),s===BD&&r&&(s=LD.inflateSetDictionary(i,r),s===VD?s=LD.inflate(i,o):s===GD&&(s=BD));i.avail_in>0&&s===FD&&i.state.wrap>0&&0!==e[i.next_in];)LD.inflateReset(i),s=LD.inflate(i,o);switch(s){case jD:case GD:case BD:case WD:return this.onEnd(s),this.ended=!0,!1;}if(a=i.avail_out,i.next_out&&(0===i.avail_out||s===FD))if("string"===this.options.to){let e=DN.utf8border(i.output,i.next_out),t=i.next_out-e,r=DN.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r);}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==VD||0!==a){if(s===FD)return s=LD.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break;}}return !0;},HD.prototype.onData=function(e){this.chunks.push(e);},HD.prototype.onEnd=function(e){e===VD&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=wN.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};var YD={Inflate:HD,inflate:KD,inflateRaw:function(e,t){return (t=t||{}).raw=!0,KD(e,t);},ungzip:KD,constants:CO};const{Deflate:qD,deflate:zD,deflateRaw:JD,gzip:XD}=KN,{Inflate:QD,inflate:ZD,inflateRaw:$D,ungzip:eP}=YD;var tP,iP=zD,nP=ZD;!function(e){e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE";}(tP||(tP={}));class rP{constructor(){sh(this,"_sequence",0),sh(this,"_startTime",Date.now()),sh(this,"isUseOneByte",!0);}get startTime(){const e=Date.now()-this._startTime;return e128){const i=new Uint8Array(4);i.set([1,0,0,0]);const n={id:0,length:4,data:i.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[n]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength;}else t.commonPacketHeader.length=8+t.payload.byteLength;RC("SHOW_DATASTREAM2_LOG")&&jC.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const i=new ArrayBuffer(t.commonPacketHeader.length),n=new Uint8Array(i),r=new DataView(i);let s=0;if(r.setUint16(s,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),s+=2,r.setUint32(s,t.commonPacketHeader.sequence,!0),s+=4,r.setUint16(s,t.commonStreamHeader,!0),s+=2,t.extension){const e=this.serializeExtension(t.extension);n.set(new Uint8Array(e),s),s+=e.byteLength;}if(n.set(new Uint8Array(t.payload),s),s+=t.payload.byteLength,s!==t.commonPacketHeader.length)throw Error("serialize error!");return i;}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let i=0;const n=t.getUint16(i,!0);i+=2;const r={length:16383&n,reserved:(16384&n)>>14,extension:(32768&n)>>15,sequence:t.getUint16(i+2,!0)<<16|t.getUint16(i,!0)};let s,o;if(i+=4,RC("SHOW_DATASTREAM2_LOG")&&jC.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(i,!0),i+=2,r.extension){o=this.deserializeExtension(e.slice(i)),i+=2+o.length,s=e.slice(i);let t=!1;if(o.datas.length>0){const e=o.datas.find(e=>0===e.id);if(e){t=1==(1&new DataView(e.data).getUint32(0,!0));}}s=t?this.decompress(s):s;}else s=e.slice(8);return s;}serializeExtension(e){const{profile:t,length:i,datas:n}=e,r=new ArrayBuffer(i+2),s=new Uint8Array(r),o=new DataView(r);let a=0;if(o.setUint8(a++,t),o.setUint8(a++,i),n.forEach(e=>{t?(o.setUint8(a++,e.id),o.setUint8(a++,e.length),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(o.setUint8(a++,e.id|e.length<<4),s.set(new Uint8Array(e.data),a),a+=e.data.byteLength);}),a!==i+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(i+2));return r;}deserializeExtension(e){const t=new DataView(e);let i=0;const n=t.getUint8(i);i++;const r=t.getUint8(i);i++;const s=n===tP.TWO_BYTE,o=[],a=new DataView(e,2);let c=0;for(;c>4,c++),t>0&&(i=a.buffer.slice(c+2,c+2+t),c+=i.byteLength),o.push({id:e,length:t,data:i});}if(c!==r)throw Error("parse error");return {profile:n,length:r,datas:o};}decompress(e){return nP(new Uint8Array(e));}compress(e){return iP(new Uint8Array(e));}}class sP extends dT{constructor(e,t){super(),sh(this,"_version",1),sh(this,"_type",3),sh(this,"_config",void 0),sh(this,"_originDataChannel",void 0),sh(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),sh(this,"_dataStreamPacketHandler",void 0),sh(this,"_datachannelEventMap",new Map()),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader(),this._dataStreamPacketHandler=new rP();}get id(){return this._config.id;}get ordered(){return this._config.ordered;}get maxRetransmits(){return RC("DATASTREAM_MAX_RETRANSMITS");}get metadata(){return this._config.metadata;}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting";}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null;}getChannelId(){return this.id;}getConfig(){return this._config;}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0);}async _waitTillOpen(){return new cg((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const i=setTimeout(()=>{var e;t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)));},1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e();},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT);};}else t(new Kg(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"));});}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e);}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id);}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[cb.OPEN,cb.CLOSE,cb.ERROR].forEach(t=>{const i=()=>{this.emit(t);};this._datachannelEventMap.set(t,i),e.addEventListener(t,i);});}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach(t=>{let[i,n]=t;e.removeEventListener(i,n);}),this._datachannelEventMap.clear();}}class oP extends sP{constructor(e){super(e),sh(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength0?arguments[0]:void 0));mP||(this.size=e.entries.length);},RL=SL.prototype;if(SP(RL,{append:function(e,t){var i=GP(this);UP(arguments.length,2),nL(i.entries,{key:DP(e),value:DP(t)}),mP||this.length++,i.updateURL();},delete:function(e){for(var t=GP(this),i=UP(arguments.length,1),n=t.entries,r=DP(e),s=i<2?void 0:arguments[1],o=void 0===s?s:DP(s),a=0;at.key?1:-1;}),e.updateURL();},forEach:function(e){for(var t,i=GP(this).entries,n=bP(e,arguments.length>1?arguments[1]:void 0),r=0;r1?vL(arguments[1]):{});}}),yP(qP)){var yL=function(e){return vP(this,JP),new qP(e,arguments.length>1?vL(arguments[1]):{});};JP.constructor=yL,yL.prototype=JP,hP({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:yL});}}var AL,bL={URLSearchParams:SL,getState:GP},wL=N,OL=d,NL=L,DL=n,PL=Ys,LL=ko,kL=k,ML=Je,UL=K,xL=Object.assign,VL=Object.defineProperty,FL=OL([].concat),BL=!xL||DL(function(){if(wL&&1!==xL({b:1},xL(VL({},"a",{enumerable:!0,get:function(){VL(this,"b",{value:3,enumerable:!1});}}),{b:2})).b)return !0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach(function(e){t[e]=e;}),7!=xL({},e)[i]||PL(xL({},t)).join("")!=n;})?function(e,t){for(var i=ML(e),n=arguments.length,r=1,s=LL.f,o=kL.f;n>r;)for(var a,c=UL(arguments[r++]),d=s?FL(PL(c),s(c)):PL(c),l=d.length,u=0;l>u;)a=d[u++],wL&&!NL(o,c,a)||(i[a]=c[a]);return i;}:xL,jL=ii,GL=Hp,WL=Xt,HL=L,KL=Je,YL=function(e,t,i,n){try{return n?t(jL(i)[0],i[1]):t(i);}catch(t){GL(e,"throw",t);}},qL=bp,zL=ls,JL=Bi,XL=Yr,QL=Bp,ZL=Lp,$L=Array,ek=d,tk=2147483647,ik=/[^\0-\u007E]/,nk=/[.\u3002\uFF0E\uFF61]/g,rk="Overflow: input needs wider integers to process",sk=RangeError,ok=ek(nk.exec),ak=Math.floor,ck=String.fromCharCode,dk=ek("".charCodeAt),lk=ek([].join),uk=ek([].push),hk=ek("".replace),pk=ek("".split),_k=ek("".toLowerCase),Ek=function(e){return e+22+75*(e<26);},mk=function(e,t,i){var n=0;for(e=i?ak(e/700):e>>1,e+=ak(e/t);e>455;)e=ak(e/35),n+=36;return ak(n+36*e/(e+38));},fk=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i=55296&&r<=56319&&i=s&&nak((tk-o)/u))throw sk(rk);for(o+=(l-s)*u,s=l,i=0;itk)throw sk(rk);if(n==s){for(var h=o,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;uk(t,ck(Ek(_+E%m))),h=ak(E/m),p+=36;}uk(t,ck(Ek(h))),a=mk(o,u,d==c),o=0,d++;}}o++,s++;}return lk(t,"");},gk=wi,Tk=N,Sk=lP,Rk=h,Ck=Xt,Ik=d,vk=Uo,yk=Vo,Ak=k_,bk=Ze,wk=BL,Ok=function(e){var t=KL(e),i=zL(this),n=arguments.length,r=n>1?arguments[1]:void 0,s=void 0!==r;s&&(r=WL(r,n>2?arguments[2]:void 0));var o,a,c,d,l,u,h=ZL(t),p=0;if(!h||this===$L&&qL(h))for(o=JL(t),a=i?new this(o):$L(o);o>p;p++)u=s?r(t[p],p):t[p],XL(a,p,u);else for(l=(d=QL(t,h)).next,a=i?new this():[];!(c=HL(l,d)).done;p++)u=s?YL(d,r,[c.value,p],!0):c.value,XL(a,p,u);return a.length=p,a;},Nk=wo,Dk=Yu.codeAt,Pk=function(e){var t,i,n=[],r=pk(hk(_k(e),nk,"."),".");for(t=0;t?@[\\\]^|]/,mM=/[\0\t\n\r #/:<>?@[\\\]^|]/,fM=/^[\u0000-\u0020]+/,gM=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,TM=/[\t\n\r]/g,SM=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)rM(t,e%256),e=Kk(e/256);return Jk(t,".");}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,s=0;s<8;s++)0!==e[s]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=s),++r);return r>i&&(t=n,i=r),t;}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=Xk(e[i],16),i<7&&(t+=":")));return "["+t+"]";}return e;},RM={},CM=wk({},RM,{" ":1,'"':1,"<":1,">":1,"`":1}),IM=wk({},CM,{"#":1,"?":1,"{":1,"}":1}),vM=wk({},IM,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),yM=function(e,t){var i=Dk(e,0);return i>32&&i<127&&!bk(t,e)?e:encodeURIComponent(e);},AM={ftp:21,file:null,http:80,https:443,ws:80,wss:443},bM=function(e,t){var i;return 2==e.length&&zk(cM,qk(e,0))&&(":"==(i=qk(e,1))||!t&&"|"==i);},wM=function(e){var t;return e.length>1&&bM(iM(e,0,2))&&(2==e.length||"/"===(t=qk(e,2))||"\\"===t||"?"===t||"#"===t);},OM=function(e){return "."===e||"%2e"===nM(e);},NM={},DM={},PM={},LM={},kM={},MM={},UM={},xM={},VM={},FM={},BM={},jM={},GM={},WM={},HM={},KM={},YM={},qM={},zM={},JM={},XM={},QM=function(e,t,i){var n,r,s,o=Lk(e);if(t){if(r=this.parse(o))throw Wk(r);this.searchParams=null;}else {if(void 0!==i&&(n=new QM(i,!0)),r=this.parse(o,null,n))throw Wk(r);(s=jk(new Bk())).bindURL(this),this.searchParams=s;}};QM.prototype={type:"URL",parse:function(e,t,i){var n,r,s,o,a,c=this,d=t||NM,l=0,u="",h=!1,p=!1,_=!1;for(e=Lk(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=$k(e,fM,""),e=$k(e,gM,"$1")),e=$k(e,TM,""),n=Ok(e);l<=n.length;){switch(r=n[l],d){case NM:if(!r||!zk(cM,r)){if(t)return sM;d=PM;continue;}u+=nM(r),d=DM;break;case DM:if(r&&(zk(dM,r)||"+"==r||"-"==r||"."==r))u+=nM(r);else {if(":"!=r){if(t)return sM;u="",d=PM,l=0;continue;}if(t&&(c.isSpecial()!=bk(AM,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&AM[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?d=WM:c.isSpecial()&&i&&i.scheme==c.scheme?d=LM:c.isSpecial()?d=xM:"/"==n[l+1]?(d=kM,l++):(c.cannotBeABaseURL=!0,Zk(c.path,""),d=zM);}break;case PM:if(!i||i.cannotBeABaseURL&&"#"!=r)return sM;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=Nk(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=XM;break;}d="file"==i.scheme?WM:MM;continue;case LM:if("/"!=r||"/"!=n[l+1]){d=MM;continue;}d=VM,l++;break;case kM:if("/"==r){d=FM;break;}d=qM;continue;case MM:if(c.scheme=i.scheme,r==AL)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())d=UM;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.path.length--,d=qM;continue;}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}break;case UM:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=qM;continue;}d=FM;}else d=VM;break;case xM:if(d=VM,"/"!=r||"/"!=qk(u,l+1))continue;l++;break;case VM:if("/"!=r&&"\\"!=r){d=FM;continue;}break;case FM:if("@"==r){h&&(u="%40"+u),h=!0,s=Ok(u);for(var E=0;E65535)return aM;c.port=c.isSpecial()&&g===AM[c.scheme]?null:g,u="";}if(t)return;d=YM;continue;}return aM;}u+=r;break;case WM:if(c.scheme="file","/"==r||"\\"==r)d=HM;else {if(!i||"file"!=i.scheme){d=qM;continue;}if(r==AL)c.host=i.host,c.path=Nk(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=Nk(i.path),c.query="",d=JM;else {if("#"!=r){wM(Jk(Nk(n,l),""))||(c.host=i.host,c.path=Nk(i.path),c.shortenPath()),d=qM;continue;}c.host=i.host,c.path=Nk(i.path),c.query=i.query,c.fragment="",d=XM;}}break;case HM:if("/"==r||"\\"==r){d=KM;break;}i&&"file"==i.scheme&&!wM(Jk(Nk(n,l),""))&&(bM(i.path[0],!0)?Zk(c.path,i.path[0]):c.host=i.host),d=qM;continue;case KM:if(r==AL||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&bM(u))d=qM;else if(""==u){if(c.host="",t)return;d=YM;}else {if(o=c.parseHost(u))return o;if("localhost"==c.host&&(c.host=""),t)return;u="",d=YM;}continue;}u+=r;break;case YM:if(c.isSpecial()){if(d=qM,"/"!=r&&"\\"!=r)continue;}else if(t||"?"!=r){if(t||"#"!=r){if(r!=AL&&(d=qM,"/"!=r))continue;}else c.fragment="",d=XM;}else c.query="",d=JM;break;case qM:if(r==AL||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=nM(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,"")):OM(u)?"/"==r||"\\"==r&&c.isSpecial()||Zk(c.path,""):("file"==c.scheme&&!c.path.length&&bM(u)&&(c.host&&(c.host=""),u=qk(u,0)+":"),Zk(c.path,u)),u="","file"==c.scheme&&(r==AL||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)eM(c.path);"?"==r?(c.query="",d=JM):"#"==r&&(c.fragment="",d=XM);}else u+=yM(r,IM);break;case zM:"?"==r?(c.query="",d=JM):"#"==r?(c.fragment="",d=XM):r!=AL&&(c.path[0]+=yM(r,RM));break;case JM:t||"#"!=r?r!=AL&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":yM(r,RM)):(c.fragment="",d=XM);break;case XM:r!=AL&&(c.fragment+=yM(r,CM));}l++;}},parseHost:function(e){var t,i,n;if("["==qk(e,0)){if("]"!=qk(e,e.length-1))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return qk(e,u);};if(":"==h()){if(":"!=qk(e,1))return;u+=2,l=++d;}for(;h();){if(8==d)return;if(":"!=h()){for(t=i=0;i<4&&zk(_M,h());)t=16*t+Hk(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,d>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++;}if(!zk(lM,h()))return;for(;zk(lM,h());){if(s=Hk(h(),10),null===r)r=s;else {if(0==r)return;r=10*r+s;}if(r>255)return;u++;}c[d]=256*c[d]+r,2!=++n&&4!=n||d++;}if(4!=n)return;break;}if(":"==h()){if(u++,!h())return;}else if(h())return;c[d++]=t;}else {if(null!==l)return;u++,l=++d;}}if(null!==l)for(o=d-l,d=7;0!=d&&o>0;)a=c[d],c[d--]=c[l+o-1],c[l+--o]=a;else if(8!=d)return;return c;}(iM(e,1,-1)),!t)return oM;this.host=t;}else if(this.isSpecial()){if(e=Pk(e),zk(EM,e))return oM;if(t=function(e){var t,i,n,r,s,o,a,c=tM(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n1&&"0"==qk(r,0)&&(s=zk(uM,r)?16:8,r=iM(r,8==s?1:2)),""===r)o=0;else {if(!zk(10==s?pM:8==s?hM:_M,r))return e;o=Hk(r,s);}Zk(i,o);}for(n=0;n=Yk(256,5-t))return null;}else if(o>255)return null;for(a=Qk(i),n=0;n1?arguments[1]:void 0,n=Vk(t,new QM(e,!1,i));Tk||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash());},$M=ZM.prototype,eU=function(e,t){return {get:function(){return Fk(this)[e]();},set:t&&function(e){return Fk(this)[t](e);},configurable:!0,enumerable:!0};};if(Tk&&(yk($M,"href",eU("serialize","setHref")),yk($M,"origin",eU("getOrigin")),yk($M,"protocol",eU("getProtocol","setProtocol")),yk($M,"username",eU("getUsername","setUsername")),yk($M,"password",eU("getPassword","setPassword")),yk($M,"host",eU("getHost","setHost")),yk($M,"hostname",eU("getHostname","setHostname")),yk($M,"port",eU("getPort","setPort")),yk($M,"pathname",eU("getPathname","setPathname")),yk($M,"search",eU("getSearch","setSearch")),yk($M,"searchParams",eU("getSearchParams")),yk($M,"hash",eU("getHash","setHash"))),vk($M,"toJSON",function(){return Fk(this).serialize();},{enumerable:!0}),vk($M,"toString",function(){return Fk(this).serialize();},{enumerable:!0}),Gk){var tU=Gk.createObjectURL,iU=Gk.revokeObjectURL;tU&&vk(ZM,"createObjectURL",Ck(tU,Gk)),iU&&vk(ZM,"revokeObjectURL",Ck(iU,Gk));}kk(ZM,"URL"),gk({global:!0,constructor:!0,forced:!Sk,sham:!Tk},{URL:ZM});var nU=wi,rU=n,sU=H_,oU=pn,aU=lP,cU=ae("URL");nU({target:"URL",stat:!0,forced:!(aU&&rU(function(){cU.canParse();}))},{canParse:function(e){var t=sU(arguments.length,1),i=oU(e),n=t<2||void 0===arguments[1]?void 0:oU(arguments[1]);try{return !!new cU(i,n);}catch(e){return !1;}}});var dU=i(ie.URL);function lU(){const e=new Blob([atob("ZnVuY3Rpb24gZShlKXtjb25zdCB0PW5ldyBEYXRhVmlldyhlLmRhdGEpO2lmKDA9PT10LmdldFVpbnQ4KDApJiYwPT09dC5nZXRVaW50OCgxKSYmMD09PXQuZ2V0VWludDgoMikmJjE9PT10LmdldFVpbnQ4KDMpJiY2PT09dC5nZXRVaW50OCg0KSl7bGV0IG49NixyPTAsbz0wO2Zvcig7MjU1PT09KG89dC5nZXRVaW50OChuKyspKTspcis9MjU1O3IrPW87Y29uc3QgYT1mdW5jdGlvbihlLHQsbil7bGV0IHI9bmV3IFVpbnQ4QXJyYXkoZSx0LG4pLG89W10sYT0wO2Zvcig7YTxuOylhKzM8biYmMD09PXJbYV0mJjA9PT1yW2ErMV0mJjM9PT1yW2ErMl0mJigwPT09clthKzNdfHwxPT09clthKzNdfHwyPT09clthKzNdfHwzPT09clthKzNdKT8oby5wdXNoKHJbYV0sclthKzFdLHJbYSszXSksYSs9NCk6KG8ucHVzaChyW2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShvKX0oZS5kYXRhLG4scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfXJldHVybiBudWxsfWZ1bmN0aW9uIHQoZSx0KXtjb25zdCBuPWZ1bmN0aW9uKGUpe2NvbnN0IHQ9ZS5sZW5ndGg7bGV0IG49W10scj0wO2Zvcig7cjx0OylyKzI8dCYmMD09PWVbcl0mJjA9PT1lW3IrMV0mJigwPT09ZVtyKzJdfHwxPT09ZVtyKzJdfHwyPT09ZVtyKzJdfHwzPT09ZVtyKzJdKT8obi5wdXNoKGVbcl0sZVtyKzFdLDMsZVtyKzJdKSxyKz0zKToobi5wdXNoKGVbcl0pLHIrKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KG4pfSh0KSxyPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihyLzI1NSksYT1yJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK3IrZS5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBpPTA7Zm9yKDtpPG87KXNbNitpXT0yNTUsaSsrO3JldHVybiBzWzYraV09YSxpKysscy5zZXQobiw2K2kpLHMuc2V0KG5ldyBVaW50OEFycmF5KGUpLDYraStyKSxzLmJ1ZmZlcn1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIlNhZmFyaSIpPi0xJiYtMT09PW5hdmlnYXRvci51c2VyQWdlbnQuaW5kZXhPZigiQ2hyb21lIikmJihzZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXI7bGV0IG89W107ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPWU9PntlLmRhdGEuc2VpJiZvLnB1c2goZS5kYXRhLnNlaSl9LHNlbGYucG9zdE1lc3NhZ2UoInN0YXJ0ZWQiKTtjb25zdCBhPXIucmVhZGFibGUuZ2V0UmVhZGVyKCkscz1yLndyaXRhYmxlLmdldFdyaXRlcigpOyJyeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2EucmVhZCgpLnRoZW4oKHI9PntpZighci5kb25lKXtpZihyLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZShyLnZhbHVlKTt0JiZuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOnR9KX1zLndyaXRlKHIudmFsdWUpLG4ub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQobil9fSkpfShyKToidHgiPT09ci5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIGUobil7YS5yZWFkKCkudGhlbigocj0+e2lmKCFyLmRvbmUpe2lmKHIudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgZT1vLnNoaWZ0KCk7ZSYmKHIudmFsdWUuZGF0YT10KHIudmFsdWUuZGF0YSxlKSl9cy53cml0ZShyLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0ocil9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKSk7Cg==")],{type:"text/javascript"});return setTimeout(()=>dU.revokeObjectURL(e),0),new Worker(dU.createObjectURL(e));}const uU=new Map();const hU=new Map();async function pU(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(hU.has(e))return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.error("create audio-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n);}});n.readable.pipeThrough(r).pipeTo(n.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>n.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i));},t.worker=n;}function i(){e.track.removeEventListener("ended",i),function(e){const t=hU.get(e);if(t){hU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate();}catch(e){jC.warning(e&&e.message);}}}(e);}hU.set(e,t),e.track.addEventListener("ended",i);}function _U(e){const t=new DataView(e.data);if(0===t.getUint8(0)&&0===t.getUint8(1)&&0===t.getUint8(2)&&1===t.getUint8(3)&&6===t.getUint8(4)){let i=6,n=0,r=0;for(;255===(r=t.getUint8(i++));)n+=255;n+=r;const s=function(e,t,i){let n=new Uint8Array(e,t,i),r=[],s=0;for(;s1&&void 0!==arguments[1]?arguments[1]:{};if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(!e.track)return;if(fU.has(e)){const i=fU.get(e);return void(i&&(i.onSei=t.onSei));}const i={track:e.track,onSei:t.onSei};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let t=null;try{t=e.createEncodedStreams();}catch(e){return void jC.error("create video-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const s=_U(t);s&&i.onSei&&i.onSei(s),r.enqueue(t);}});t.readable.pipeThrough(r).pipeTo(t.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const t=lU(),r=new MessageChannel();await new cg(e=>t.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(t,{name:"rx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>t.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id?(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n)):t.data.sei&&i.onSei&&i.onSei(t.data.sei);},i.worker=t;}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n);}!function(e){const t=fU.get(e);if(t){fU.delete(e);try{var i,n;null===(i=t.controller)||void 0===i||i.terminate(),null===(n=t.worker)||void 0===n||n.terminate();}catch(e){jC.warning(e&&e.message);}}}(e);}fU.set(e,i),e.track.addEventListener("ended",n);}!function(){const e=Sg();CA.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return !0;return !1;}(),CA.getStreamFromExtension=e.name===Eg.CHROME&&Number(e.version)>34,CA.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return !1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return !1;const e=new RTCPeerConnection();let t=!1;try{e.addTransceiver("audio"),t=!0;}catch(e){}return e.close(),t;}(),CA.supportMinBitrate=e.name===Eg.CHROME||e.name===Eg.EDGE,CA.supportSetRtpSenderParameters=function(){const e=Sg();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return !1;return !!jg()||!(!bg()&&!Ig())||e.name===Eg.FIREFOX&&Number(e.version)>=64;}(),e.name===Eg.SAFARI&&(Number(e.version)>=14?CA.supportDualStream=!0:CA.supportDualStream=!1),CA.webAudioMediaStreamDest=function(){const e=Sg();if(e.name===Eg.SAFARI&&Number(e.version)<12)return !1;return !0;}(),CA.supportReplaceTrack=function(){if(!window.RTCRtpSender)return !1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return !0;return !1;}(),CA.supportWebGL="undefined"!=typeof WebGLRenderingContext,CA.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,jg()||(CA.webAudioWithAEC=!0),CA.supportShareAudio=function(){const e=Sg();if((e.os===_g.WIN_10||e.os===_g.WIN_81||e.os===_g.WIN_7||e.os===_g.LINUX||e.os===_g.MAC_OS||e.os===_g.CHROMIUM_OS)&&e.name===Eg.CHROME&&Number(e.version)>=74)return !0;return !1;}(),CA.supportDataChannel=function(){if(Ng(76)||function(e){const t=Sg();return !(t.name!==Eg.FIREFOX||!t.osVersion)&&Number(t.version)>=e;}(68)||function(e){const t=Sg();return !(t.name!==Eg.SAFARI||!t.osVersion)&&Number(t.version)>=e;}(14))return !0;return !1;}(),CA.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return !wg()&&!!e&&e.prototype.setConfiguration instanceof Function;}(),CA.supportWebRTCEncodedTransform=function(){const e=Sg();return "Chrome"===e.name&&Number(e.version)>=86||"Safari"===e.name&&Number(e.version)>=15;}(),CA.supportWebRTCInsertableStream=function(){const e=Sg();return (e.name===Eg.CHROME||e.name===Eg.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window;}(),KT(()=>{CA.supportDualStreamEncoding=function(){const e=Sg();if(RC("DISABLE_WEBAUDIO"))return !0;return "Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&RC("CHROME_DUAL_STREAM_USE_ENCODING"));}(),jC.info("browser compatibility",JSON.stringify(CA),JSON.stringify(e));});}();class TU extends dT{constructor(){super(...arguments),sh(this,"resultStorage",new Map());}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t));}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i));}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t));}setRemoteVideoStats(e,t){const i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t));}record(e,t,i){if(RC("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){var r;const i=bn(r=n.result).call(r,!0);n.isPrevNormal&&!i&&this.emit("exception",SU[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",SU[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[];}}checkAudioOutputLevel(e){return !(e.receiveBitrate>0&&0===e.receiveLevel);}checkAudioInputLevel(e,t){return t instanceof nw&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel;}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=Sy(t._encoderConfig.frameRate));const n=e.captureFrameRate;return !i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=1);}checkFramerateSent(e){return !(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1);}checkSendVideoBitrate(e,t){return !!t.muted||0!==e.sendBitrate;}checkSendAudioBitrate(e,t){return t instanceof nw&&!t.isActive||!!t.muted||0!==e.sendBitrate;}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate;}}const SU={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};const RU=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t));}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t));}measureFromSubscribeStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime);}return 0;}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime);}return 0;}}();function CU(e,t){this.v=e,this.k=t;}function IU(e){return new CU(e,0);}var vU=ag,yU=um;wi({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=yU.f(this);return {promise:e.promise,resolve:e.resolve,reject:e.reject};}});var AU=um,bU=YE;wi({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=AU.f(this),i=bU(e);return (i.error?t.reject:t.resolve)(i.value),t.promise;}});var wU=i(vU),OU=Fo.f("asyncIterator"),NU=i(OU);function DU(e){var t,i;function n(t,i){try{var s=e[t](i),o=s.value,a=o instanceof CU;wU.resolve(a?o.v:o).then(function(i){if(a){var c="return"===t?"return":"next";if(!o.k||i.done)return n(c,i);i=e[c](i).value;}r(s.done?"return":"normal",i);},function(e){n("throw",e);});}catch(e){r("throw",e);}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1});}(t=t.next)?n(t.key,t.arg):i=null;}this._invoke=function(e,r){return new wU(function(s,o){var a={key:e,arg:r,resolve:s,reject:o,next:null};i?i=i.next=a:(t=i=a,n(e,r));});},"function"!=typeof e.return&&(this.return=void 0);}function PU(e){return function(){return new DU(e.apply(this,arguments));};}DU.prototype["function"==typeof xu&&NU||"@@asyncIterator"]=function(){return this;},DU.prototype.next=function(e){return this._invoke("next",e);},DU.prototype.throw=function(e){return this._invoke("throw",e);},DU.prototype.return=function(e){return this._invoke("return",e);};var LU=i(ie.Object.getOwnPropertySymbols),kU=wi,MU=Ki.indexOf,UU=Ih,xU=v([].indexOf),VU=!!xU&&1/xU([1],1,-0)<0;kU({target:"Array",proto:!0,forced:VU||!UU("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return VU?xU(this,e,t)||0:MU(this,e,t);}});var FU=zi("Array").indexOf,BU=l,jU=FU,GU=Array.prototype,WU=i(function(e){var t=e.indexOf;return e===GU||BU(GU,e)&&t===GU.indexOf?jU:t;}),HU=Je,KU=Ys;wi({target:"Object",stat:!0,forced:n(function(){KU(1);})},{keys:function(e){return KU(HU(e));}});var YU=i(ie.Object.keys);function qU(e,t){if(null==e)return {};var i,n,r=function(e,t){if(null==e)return {};var i,n,r={},s=YU(e);for(n=0;n=0||(r[i]=e[i]);return r;}(e,t);if(LU){var s=LU(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i]);}return r;}var zU={exports:{}};!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>C,Printer:()=>b,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),s=" ";let o;function a(e){return e>="0"&&e<="9";}function c(e){return e>="!"&&e<="~";}function d(e){return c(e)||e>="€"&&e<="ÿ";}function l(e){return "!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~";}function u(e){return e>="1"&&e<="9";}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z";}function p(e){return "d"===e||"h"===e||"m"===e||"s"===e;}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ";}function E(e){return h(e)||a(e)||"+"===e||"/"===e;}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e;}function f(e){return h(e)||a(e)||"+"===e||"/"===e;}function g(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function T(e){for(var t=1;t=0&&n<=255)return i;throw new Error("Invalid decimal uchar");}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return ":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),i):i;}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i);}catch(e){}return i;}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i);}catch(e){}return i;}return i;}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i;}consumeHex4(e,t){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break;}var n;return t+i;}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i;}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d);}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t);}catch(i){return this.consumeExtnAddr(e,t);}}}consumeIP6MulticastAddress(e,t){const i=this.consumeHexpart(e,t);return "/"===e[i]?this.consumeInteger(e,i+1):i;}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw new Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i);}return "/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i)),i;}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t;}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t;}consumeToken(e,t){return this.consumeOneOrMore(e,t,l);}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(u(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i;}consumeAddress(e,t){return this.consumeTill(e,t,s);}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i;}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t;}consumePort(e,t){return this.consumeOneOrMore(e,t,a);}consume(e,t,i){for(let n=0;n=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n));}return t+i.length;}consumeTill(e,t,i){let n=t;for(;n!!e.trim()).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),s=this.parseInformation(),o=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return {version:i,origin:n,sessionName:r,information:s,uri:o,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_};}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e;}probeEOL(e){for(let t=0;t=.");const i=e[0];if("="!==e[1])throw new Error('Invalid sdp line, should be a single character followed by an "=" sign.');return {type:i,value:e.slice(2),line:t,cur:0};}parseSessionAttribute(){const e=new v();for(;this.currentLinel(e)&&":"!==e),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++;}return e.digest();}parseMediaAttributes(e){const t=new y(e);for(;this.currentLinel(e)&&":"!==e),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++;}return t.digest();}parseKey(){const e=this.getCurrentRecord();if(e.type===o.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.");}}parseZone(){const e=this.getCurrentRecord();if(e.type===o.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n});}catch(e){break;}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t;}return [];}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==o.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++;}}return e;}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime));}catch(e){break;}if(0===t.length)throw new Error("Invalid typed time.");return t;}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i};}parseBandWidth(){const e=[];for(;this.currentLineo)throw new Error("error in length, should be less or equal than ".concat(o," characters."));return e._cur=n,r;}consumeAttributeSpace(e){if(e.attValue[e._cur]!==s)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1;}extract(e,t,...i){if(!e.attValue)throw new Error("Nothing to extract from attValue.");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r;}atEnd(e){if(!e.attValue)throw new Error();return e._cur>=e.attValue.length;}peekChar(e){if(!e.attValue)throw new Error();return e.attValue[e._cur];}peek(e,t){if(!e.attValue)throw new Error();for(let i=0;ie!==s&&_(e));i.push({name:t,value:n});}this.attributes.identities.push({assertionValue:t,extensions:i});}parseMsidSemantic(e){this.peekChar(e)===s&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e);}catch(e){break;}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break;}{const i=this.extract(e,this.consumeTill,s);t.identifierList.push(i);}}this.attributes.msidSemantic=t;}}class y extends I{constructor(e){super(),S(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]};}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e);}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t;}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error");}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const o=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:o,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===s;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c);}this.attributes.candidates.push(l);}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e);}catch(e){break;}}this.attributes.remoteCandidatesList.push(t);}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0;}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]});}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill);}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill);}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField;}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find(e=>e.ssrcId===parseInt(t,10));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}});}parseFmtp(e){const t=this.extract(e,this.consumeTill,s);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach(e=>{let[t,i]=e.split("=");t=t.trim();const r="string"==typeof i?i.trim():null;"string"==typeof t&&t.length>0&&(n[t]=r);});const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}});}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n;}return t;}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,s),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,s);let n;if("trr-int"===i)n={type:i,interval:this.extract(e,this.consumeTill)};else {const t={type:i};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===s&&(t.additional=this.extract(e,this.consumeTill))),n=t;}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else {const e=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]});}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0;}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0;}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0;}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t;}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===s&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t);}parseImageAttr(e){this.attributes.imageattr.push(e.attValue);}parseRid(e){const t=this.extractOneOrMore(e,e=>h(e)||a(e)||"_"===e||"-"===e);this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===s){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",");}catch(e){break;}}i.payloads=t,this.peekChar(e)===s&&this.extract(e,this.consume,s);}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break;}default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n);}}try{this.extract(e,this.consume,";");}catch(e){break;}}}this.attributes.rids.push(i);}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill);}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5]);}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0]);}digest(){return this.digested=!0,this.attributes;}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken);}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10));}catch(e){break;}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i});}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e;}class b{constructor(){A(this,"eol",r);}print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i;}printVersion(e){return "v=".concat(e).concat(this.eol);}printOrigin(e){return "o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol);}printSessionName(e){return e?"s=".concat(e).concat(this.eol):"";}printInformation(e){return e?"i=".concat(e).concat(this.eol):"";}printUri(e){return e?"u=".concat(e).concat(this.eol):"";}printEmail(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t;}printPhone(e){let t="";for(const i of e)t+="e=".concat(i).concat(this.eol);return t;}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):"";}printBandwidth(e){let t="";for(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t;}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of i.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map(e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime)).join(" ")).concat(this.eol),t+=this.eol);}return t;}printKey(e){return e?"k=".concat(e).concat(this.eol):"";}printAttributes(e){let t="";for(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t;}printMediaDescription(e){let t="";for(const i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t;}printConnections(e){let t="";for(const i of e)t+=this.printConnection(i);return t;}printMedia(e){return "m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol);}printSessionAttributes(e){return new O(this.eol).print(e);}printMediaAttributes(e){return new N(this.eol).print(e);}}class w{constructor(e){A(this,"eol",void 0),this.eol=e;}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol);}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol);}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(s)).concat(this.eol);}printFingerprints(e){return e.length>0?e.map(e=>"a=fingerprint:".concat(e.hashFunction).concat(s).concat(e.fingerprint)).join(this.eol)+this.eol:"";}printExtmap(e){return e.map(e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(s).concat(e.extensionName).concat(e.extensionAttributes?"".concat(s).concat(e.extensionAttributes):"").concat(this.eol)).join("");}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol);}printUnrecognized(e){return e.map(e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol)).join("");}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t;}printGroups(e){let t="";return e.length>0&&(t+=e.map(e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map(e=>"".concat(s).concat(e)).join("")).concat(this.eol)).join("")),t;}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol;}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):"";}printIdentity(e){return 0===e.length?"":e.map(e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map(e=>"".concat(s).concat(e.name).concat(e.value?"=".concat(e.value):"")))).join(this.eol)+this.eol;}printMsidSemantic(e){if(!e)return "";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(s,"*"):e.identifierList.length>0&&(t+=e.identifierList.map(e=>"".concat(s).concat(e))),t+this.eol;}}class N extends w{print(e){const t=e.attributes;let i="";return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized),i;}printCandidates(e){return e.map(e=>"a=candidate:".concat(e.foundation).concat(s).concat(e.componentId).concat(s).concat(e.transport).concat(s).concat(e.priority).concat(s).concat(e.connectionAddress).concat(s).concat(e.port).concat(s,"typ").concat(s).concat(e.type).concat(e.relAddr?"".concat(s,"raddr").concat(s).concat(e.relAddr):"").concat(e.relPort?"".concat(s,"rport").concat(s).concat(e.relPort):"").concat(Object.keys(e.extension).map(t=>"".concat(s).concat(t).concat(s).concat(e.extension[t])).join("")).concat(this.eol)).join("");}printRemoteCandidatesList(e){return e.map(e=>"a=remote-candidates:".concat(e.join(s)).concat(this.eol)).join("");}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol;}printRTPRelated(e){if(!e.payloads)return "";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map(e=>this.printRTCPFeedback("*",e)).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map(t=>this.printRTCPFeedback(e.payloadType,t)).join("");return i;}printFmtp(e,t){if(!t)return "";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(s).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(s).concat(Object.keys(t.parameters).map(e=>"".concat(e,"=").concat(t.parameters[e])).join(";")).concat(this.eol);}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(s).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):"";}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(s),n=t;return "trr-int"===n.type?i+="ttr-int".concat(s).concat(n.interval):(i+="".concat(n.type),n.parameter&&(i+="".concat(s).concat(n.parameter),n.additional&&(i+="".concat(s).concat(n.additional)))),i+this.eol;}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol);}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol);}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol);}printSSRC(e){return e.map(e=>Object.keys(e.attributes).map(t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(s).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol)).join("")).join("");}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol);}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol);}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol);}printRTCP(e){if(void 0===e)return "";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(s).concat(e.netType)),e.addressType&&(t+="".concat(s).concat(e.addressType)),e.address&&(t+="".concat(s).concat(e.address)),t+this.eol;}printMSId(e){return e.map(e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(s).concat(e.appdata):"").concat(this.eol)).join("");}printImageattr(e){return e.map(e=>"a=imageattr:".concat(e).concat(this.eol)).join("");}printRid(e){return e.map(e=>{let t="a=rid:".concat(e.id).concat(s).concat(e.direction);return e.payloads&&(t+="".concat(s,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(s).concat(e.params.map(e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val)).join(";"))),t+this.eol;}).join("");}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol);}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol);}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol);}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol);}printSSRCGroups(e){return e.map(e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map(e=>"".concat(s).concat(e.toString(10))).join("")).concat(this.eol)).join("");}}function D(e){return new C().parse(e);}function P(e,t){return new b().print(e,t);}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports;}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]});},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},i(8);})();}(zU);var JU=zU.exports;function XU(e){if(Array.isArray(e))return e.map(e=>e);if(!QU(e))return e;const t={};for(const i in e){const n=e[i];QU(n)||Array.isArray(n)?t[i]=XU(n):t[i]=n;}return t;}function QU(e){return !("object"!=typeof e||Array.isArray(e)||!e);}class ZU{constructor(e){sh(this,"input",[]),sh(this,"size",void 0),this.size=e;}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1);}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length;}}const $U={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},ex={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:$U,remoteCandidate:$U}},tx={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0},ix={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},nx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},rx={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function sx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function ox(e){for(var t=1;t{this.updateStats();},this.options.updateInterval);}getStats(){return this.stats;}getSelectedCandidatePair(){return new cg(e=>{e({local:ox({},$U),remote:ox({},$U)});});}setVideoIsReady(e){this.videoIsReady=e;}setVideoIsReady2(e,t){this.videoIsReady2[e]=t;}getVideoIsReady(e){return this.videoIsReady2[e]||!1;}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0;}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,s=0,o=0;for(const a of i)e[a].forEach((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,s+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d);});e.sendPacketLossRate=n<=0||s<=0?0:s/(n+s),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o);}}function cx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function dx(e){for(var t=1;t"ssrc"===e.type);this.processSSRCStats(i);const n=t.find(e=>"VideoBwe"===e.type);n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats;}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth);}processSSRCStats(e){e.forEach(e=>{var t;const i=bn(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const t=XU(ix);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break;}case"video_recv":{const t=XU(tx),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break;}case"audio_send":{const t=XU(nx);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break;}}});}_getStats(){return new cg((e,t)=>{this.pc.getStats(e,t);});}statsResponsesToObjects(e){const t=[];return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach(t=>{i[t]=e.stat(t);}),t.push(i);}),t;}}function ux(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function hx(e){for(var t=1;t{switch(e.type){case aI.OUTBOUND:case aI.INBOUND:{const t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,n=!t&&!("frameWidth"in e);e.type===aI.OUTBOUND?"audio"===t||n?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===aI.INBOUND&&("audio"===t||n?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break;}case aI.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break;}case aI.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e);}}),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats;}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:hx({},$U),remote:hx({},$U)};return e.forEach(i=>{let n;if(i.type===aI.TRANSPORT&&(n=e.get(i.selectedCandidatePairId)),i.type===aI.CANDIDATE_PAIR&&i.selected&&(n=i),n){const i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol);};if(n.localCandidateId){const r=e.get(n.localCandidateId);r&&i(t.local,r);}if(n.remoteCandidateId){const r=e.get(n.remoteCandidateId);r&&i(t.remote,r);}}}),t;}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime);}),this._stats.audioSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime);}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t);}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t);}}processCandidateStats(e){let t;e.type===aI.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===aI.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===aI.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.localCandidate)),e.type===aI.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(hx({},t),hx({},this.stats.selectedCandidatePair.remoteCandidate)));}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=XU(rx),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples);}processVideoInboundStats(e){let t=this._stats.videoRecv.find(t=>t.ssrc===e.ssrc);t||(t=XU(tx),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0;}if(i){const n=i.stats,s=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&s>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=s,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCounte.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount));}n&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:0}),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:hx({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum});}processVideoOutboundStats(e){let t=this._stats.videoSend.find(t=>t.ssrc===e.ssrc);t||(t=XU(ix),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else {const t=new ZU(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t);}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else {const t=new ZU(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t);}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else {const t=new ZU(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t);}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else {const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n;}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount);}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else {const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=XU(nx),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else {const i=this.findRemoteStatsId(e.ssrc,aI.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t);}}findRemoteStatsId(e,t){var i;const n=Array.from(NI(i=this.report).call(i)).find(i=>i.type===t&&i.ssrc===e);return n?n.id:null;}processVideoMediaSource(e,t){const i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond});}processAudioMediaSource(e,t){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel);}processVideoTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null==a?void 0:a.framesSent)&&void 0!==n?n:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(s=null==a?void 0:a.frameHeight)&&void 0!==s?s:e.frameHeight,u=null!==(o=null==a?void 0:a.framesPerSecond)&&void 0!==o?o:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0});}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)};}processVideoTrackReceiverStats(e,t,i){var n,r,s,o,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(s=null==c?void 0:c.frameHeight)&&void 0!==s?s:e.frameHeight,h=null!==(o=null==c?void 0:c.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:n||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0};}if(h&&p){const e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=p-e.jitterBufferEmittedCount;n>0&&(t=1e3*(h-e.jitterBufferDelay)/n),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs});}}processAudioTrackSenderStats(e,t,i){var n,r,s,o;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(s=null!==(o=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==o?o:e.echoReturnLossEnhancement)&&void 0!==s?s:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d;}processAudioTrackReceiverStats(e,t,i){var n,r,s,o,a,c,d;const l=t?this.report.get(t):void 0,u=null!==(n=null==l?void 0:l.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==l?void 0:l.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(s=null==l?void 0:l.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,_=null!==(o=null==l?void 0:l.jitterBufferEmittedCount)&&void 0!==o?o:e.jitterBufferEmittedCount,E=null!==(a=null==l?void 0:l.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==l?void 0:l.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==l?void 0:l.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(u&&h&&(i.accelerateRate=u/h),p&&_){const e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const n=_-e.jitterBufferEmittedCount;n>0&&(t=1e3*(p-e.jitterBufferDelay)/n),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_,jitterBufferMs:i.jitterBufferMs});}i.outputLevel=E;let g=1920;m&&h&&(g=h/m/50,i.receivedFrames=Math.round(h/g)),f&&(i.droppedFrames=Math.round(f/g));}processRemoteInboundStats(e,t){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp));}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return "";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:"";}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach(t=>{e+=t.diffMean();}),this.mediaBytesRetransmit.forEach(e=>{t=null===t?e.diffMean():t+e.diffMean();}),this.mediaBytesTargetEncode.forEach(e=>{i=null===i?e.diffMean():i+e.diffMean();});const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3));}}class _x extends ax{updateStats(){return cg.resolve();}}function Ex(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const s=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null;}();return s?s<76?new lx(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(e){return !!window.RTCStatsReport&&e.getStats()instanceof cg;}(e)?new px(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new _x(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r});}function mx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function fx(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:s,filterAudioFec:o,filterAudioCodec:a,filterVideoCodec:c}=t,{useXR:d}=i;let l=[],u=[],h=[],p=[],_=!1,E=!1;if(JU.parse(e).mediaDescriptions.forEach(e=>{n&&n!==e.attributes.direction||("video"!==e.media.mediaType||_||(u=e.attributes.payloads,p=e.attributes.extmaps,_=!0),"audio"!==e.media.mediaType||E||(l=e.attributes.payloads,h=e.attributes.extmaps,E=!0));}),!p||0===u.length)throw new Error("Cannot get video capabilities from SDP.");if(!h||0===l.length)throw new Error("Cannot get audio capabilities from SDP.");u.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"});}),l.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),d&&e.rtcpFeedbacks.push({type:"rrtr"});}),r&&(l=l.filter(e=>{var t;return "rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());}),u=u.filter(e=>{var t;return "rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());})),s&&(u=u.filter(e=>{var t;return !/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"");})),o&&(l=l.filter(e=>{var t;return !/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"");})),a&&(null==a?void 0:a.length)>0&&(l=l.filter(e=>{var t;return bn(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");})),c&&(null==c?void 0:c.length)>0&&(u=u.filter(e=>{var t;return bn(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"");}));const m=RC("UNSUPPORTED_VIDEO_CODEC");return m&&m.length>0&&(u=u.filter(e=>!(e.rtpMap&&bn(m).call(m,e.rtpMap.encodingName.toLowerCase())))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p};}function Tx(e){const t=JU.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n};}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t});}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return {iceParameters:i,dtlsParameters:n};}function Sx(e,t){const i=[],n=e.attributes.ssrcGroups.filter(e=>"FID"===e.semantic),r=e.attributes.ssrcGroups.find(e=>"SIM"===e.semantic),s=e.attributes.ssrcs;if(r)r.ssrcIds.forEach(e=>{var r;const s=null===(r=n.find(t=>t.ssrcIds[0]===e))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?s:void 0});});else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0});}else {if(0===s.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:s[0].ssrcId});}return i;}function Rx(e,t){const{cname:i}=e;let n;t&&t.ip&&"number"==typeof t.port?(n=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],jC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(n.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),jC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):n=e.iceParameters.candidates.map(e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}));const r={fingerprints:e.dtlsParameters.fingerprints.map(e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let o;switch(e.dtlsParameters.role){case"server":o="passive";break;case"client":o="active";break;case"auto":o="actpass";}return {dtlsParameters:r,iceParameters:s,candidates:n,rtpCapabilities:Px(e.rtpCapabilities),setup:o,cname:i};}function Cx(e,t,i){const n=[],r=[];return e.forEach(e=>{let{ssrcId:s,rtx:o}=e;const a=nS(8,"track-"),c={ssrcId:s,attributes:fx({label:a,mslabel:i=i||nS(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==o){const e={ssrcId:o,attributes:fx({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[s,o]});}}),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t;})}),{ssrcs:n,ssrcGroups:r};}function Ix(e,t){t instanceof ew&&e.attributes.payloads.forEach(e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!wg()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"));});}function vx(e){const t=e.attributes.unrecognized.findIndex(e=>"x-google-flag"===e.attField&&"conference"===e.attValue);-1!==t&&e.attributes.unrecognized.splice(t,1);}function yx(e,t){var i;if(!(t instanceof Rw&&t._encoderConfig&&-1===t._hints.indexOf(jA.SCREEN_TRACK)))return;const n=t._encoderConfig;IA().supportMinBitrate&&n.bitrateMin&&e.attributes.payloads.forEach(e=>{var t,i;bn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin));}),IA().supportMinBitrate&&!bn(i=t._hints).call(i,jA.LOW_STREAM)&&n.bitrateMax&&e.attributes.payloads.forEach(e=>{var t,i;bn(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(RC("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)));});}function Ax(e){if("video"!==e.media.mediaType)return;const t=Sg();if(t.name!==Eg.SAFARI&&t.os!==_g.IOS)return;const i=e.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==i&&e.attributes.extmaps.splice(i,1);}function bx(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);if(t){e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"});const i=function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)));}(r,e.attributes.payloads);i.forEach(e=>{e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)||e.rtcpFeedbacks.push({type:"transport-cc"});});}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}if(!0===t.remb){const t=n.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);if(t){e.attributes.extmaps.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"});const i=function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)));}(r,e.attributes.payloads);i.forEach(e=>{e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)||e.rtcpFeedbacks.push({type:"goog-remb"});});}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"goog-remb"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}}function wx(e,t,i){if(wg())return;if("video"!==e.media.mediaType)return;if(!(t instanceof Rw))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!RC("SIMULCAST"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],s=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId),o={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=new RTCPeerConnection();i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(await i.createOffer()).sdp,{send:r,recv:s,sendrecv:o}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const n=gx(i,e,t,"sendonly"),r=gx(i,e,t,"recvonly"),s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(n,r,"videoExtensions",s,o,a),Dx(n,r,"videoCodecs",s,o,a),Dx(n,r,"audioExtensions",s,o,a),Dx(n,r,"audioCodecs",s,o,a),RC("RAISE_H264_BASELINE_PRIORITY")){const e=a.videoCodecs.findIndex(e=>{var t,i;return "h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]);});if(-1!==e){const t=a.videoCodecs.findIndex(e=>{var t;return "h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase());});if(t{var t,i;return !("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]));})),-1!==t&&RC("FILTER_SEND_H264_BASELINE")&&(s.videoCodecs=s.videoCodecs.filter(e=>{var t,i;return !("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]));}));}}return {send:s,recv:o,sendrecv:a};}(e,t,n);try{i.close();}catch(e){}return {send:r,recv:s,sendrecv:o};}function Nx(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=gx(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(e,t,"videoExtensions",i,n,r),Dx(e,t,"videoCodecs",i,n,r),Dx(e,t,"audioExtensions",i,n,r),Dx(e,t,"audioCodecs",i,n,r),RC("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){const t=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])));}}return {send:i,recv:n,sendrecv:r};}function Dx(e,t,i,n,r,s){if("videoExtensions"===i||"audioExtensions"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}if("videoCodecs"===i||"audioCodecs"===i){const o=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return o.push(i),!0;})?s[i].push(e):n[i].push(e);}),void t[i].forEach((e,t)=>{-1===o.indexOf(t)&&r[i].push(e);});}}function Px(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return {send:t,recv:i};}let r,s;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s.audioCodecs=[...i.audioCodecs,...n.audioCodecs],s.videoCodecs=[...i.videoCodecs,...n.videoCodecs],s.audioExtensions=[...i.audioExtensions,...n.audioExtensions],s.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):s=n,{send:r,recv:s};}function Lx(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter(e=>{var t;return "opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase());}).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1";});}function kx(e){e.mediaDescriptions.forEach(e=>{"video"!==e.media.mediaType&&"audio"!==e.media.mediaType||e.attributes.payloads.forEach(e=>{-1===e.rtcpFeedbacks.findIndex(e=>"rrtr"===e.type)&&e.rtcpFeedbacks.push({type:"rrtr"});});});}function Mx(e,t,i,n){let r=[];if(e===av.VIDEO){if(RC("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(r=t.videoCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===RC("H264_PROFILE_LEVEL_ID");})),!Array.isArray(r)||0===r.length){let e=[];const s=[],o=[];i.videoCodecs.forEach(t=>{var i,r,a;bn(i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(i,n)&&e.push(t),bn(r=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(r,"vp8")&&s.push(t),bn(a=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").call(a,"h264")&&o.push(t);}),0===e.length&&(0!==s.length?(e=s,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: vp8"))):0!==o.length&&(e=o,jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: h264")))),0!==e.length&&(r=t.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)));}if(RC("USE_PUB_RTX")){const e=r.map(e=>e.payloadType.toString()),i=t.videoCodecs.filter(t=>t.rtpMap&&"rtx"===t.rtpMap.encodingName&&bn(e).call(e,t.fmtp&&t.fmtp.parameters.apt||""));r=[...r,...i];}0===r.length&&(jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs);}else r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,n);}),0===r.length&&(jC.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter(e=>{var t;return bn(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus");}));return r;}let Ux=class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname","o/i14u9pJrxRKAsu"),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:s,direction:o,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=o===TI.RECEIVE_ONLY?JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s;const u=o===TI.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=o===TI.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=o===TI.RECEIVE_ONLY?r.send.videoCodecs:Mx(av.VIDEO,u,h,c),_=o===TI.RECEIVE_ONLY?r.send.audioCodecs:Mx(av.AUDIO,u,h,d);for(const e of l.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=p.map(e=>e.payloadType.toString(10)),e.attributes.payloads=p,e.attributes.extmaps=u.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:4e4,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=_.map(e=>e.payloadType.toString(10)),e.attributes.payloads=_,e.attributes.extmaps=u.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1;}toString(){return JU.print(this.sessionDesc);}hasMid(e){return Array.isArray(e)?e.every(e=>this.hasMid(e)):this.sessionDesc.mediaDescriptions.some(t=>t.attributes.mid===e);}send(e,t,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:s,ssrcGroups:o}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(s);if(a){if(wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0};}return {mid:a.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,s,n);let i;return -1===t?(i=this.createOrRecycleSendMedia(e,s,o,"sendonly",n,r),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=s,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,r)),wg()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,i.attributes.mid),{needExchangeSDP:!0,mid:i.attributes.mid};}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{e.attributes.ssrcs=[];}),this.updateBundleMids();}receive(e,t,i){const n=[];return e.forEach(e=>{const r=e._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(r);let o,a=!1;-1===s?(a=!0,o=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(o=YT(this.sessionDesc.mediaDescriptions[s]),o.attributes.direction="recvonly"),n.push({mid:o.attributes.mid,needCreateTransceiver:a});}),n;}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}addRemoteCandidate(e){const{foundation:t,protocol:i,address:n,port:r,type:s,relatedAddress:o,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=i?i:"",priority:c?c+"":"",connectionAddress:null!=n?n:"",port:r?r+"":"",type:s?s+"":"",relAddr:null!=o?o:"",relPort:a?a+"":"",extension:{}};this.candidates.some(e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(e=>{e.attributes.candidates=this.candidates;}));}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates;}createOrRecycleRecvMedia(e,t,i,n,r){const s=e._mediaStreamTrack.kind,o=this.rtpCapabilities.recv,a=Mx(s,o,this.localCapabilities.send,s===av.AUDIO?r:n),c=s===av.VIDEO?o.videoExtensions:o.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:s,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(s);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l;}else this.sessionDesc.mediaDescriptions.push(l);return l;}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex(n=>{const r=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if(wg()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid);}return !1;}return r&&n.attributes.mid===i;});}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex(t=>{const i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return "0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i;});}predictReceivingMids(e){const t=[];for(let i=0;i{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}createOrRecycleSendMedia(e,t,i,n,r,s){const o=this.rtpCapabilities.send,a=e===av.VIDEO?o.videoCodecs:o.audioCodecs,c=e===av.VIDEO?o.videoExtensions:o.audioExtensions;wg()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,s);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}};const xx=["sdp"];function Vx(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function Fx(e){for(var t=1;t2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Dx(t,e,"videoExtensions",i,n,r),Dx(t,e,"videoCodecs",i,n,r),Dx(t,e,"audioExtensions",i,n,r),Dx(t,e,"audioCodecs",i,n,r),RC("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){const t=r.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])));}}return {send:i,recv:n,sendrecv:r};}(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const s=Tx(r.sdp);await this.peerConnection.setLocalDescription(r);const o=await Nx(this.filter,this.extension,r.sdp);this.localCapabilities=Px(o);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Fx(Fx({},s),{},{sdp:r.sdp});}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp);return this.initialOffer=e,Fx(Fx({},t),{},{sdp:e.sdp});}}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:t,iceParameters:i,dtlsParameters:n}=e,r=await Nx(this.filter,this.extension,t);this.remoteSDP=new Ux({remoteIceParameters:i,remoteDtlsParameters:n,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];null!=s&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach(e=>{this.peerConnection.addIceCandidate(e);}),this.pendingCandidates=[]);}catch(e){throw new Kg(Hg.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],o=n.remoteSDP.receive(e,t,i);e.forEach((e,t)=>{if(o[t].needCreateTransceiver){const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}else {const i=n.peerConnection.getTransceivers().find(e=>e.mid===o[t].mid);if(!i)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(o[t].mid));s.push(i),e._updateRtpTransceiver(i);}}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const a=o.map(e=>e.mid),c=yield IU(n.peerConnection.createOffer()),d=n.mungSendOfferSDP(c.sdp,e,a),l=JU.parse(d),u=a.map(e=>{const t=l.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));}),h=s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h;}catch(e){const t=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield IU(n.stopSending(a,!0)),e;}yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e));const p=n.remoteSDP.toString(),_=n.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield IU(n.setRemoteDescription({type:"answer",sdp:p})),s.map((e,t)=>{const i=a[t];return {localSSRC:u[t],id:i};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o||null===o.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,mid:o.mid,transceiver:o};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async mockReceive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async restartICE(t){try{if(this.store.p2pTransport===fC.Auto&&(this.store.p2pTransport=fC.SdRtn,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,IA().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:t}=Tx(e.sdp);return this.store.descriptionStart(),this.direction===TI.SEND_ONLY&&(await this.peerConnection.setLocalDescription(e)),t;}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===TI.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:t}=Tx(e.sdp);return await this.peerConnection.setLocalDescription(e),t;}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0;}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return {local:Fx(Fx({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Fx(Fx({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})};}return this.statsFilter.getSelectedCandidatePair();}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;bn(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.startICECandidate();}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)this.localCandidateAddress=e.candidate.address,null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1;}else this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount);});}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var s;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(RT(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),RC("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),bn(s=[fC.Relay,fC.SdRtn]).call(s,i)&&(r.iceTransportPolicy="relay"),RC("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(r.iceTransportPolicy="relay");})));return RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),jC.debug("P2PConnection p2pTransport is ".concat(i)),r;}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const n=[],r=e.filter(e=>e.tcpport);jC.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(i));const s=r.length>i?r[i]:r[0];switch(t){case fC.SdRtn:const t=e.filter(e=>{var t;return bn(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL;}),r=t.length>i?t[i]:t[0];r&&(n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),n.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(gy(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case fC.Relay:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(gy(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),n.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.tcpport)}));}return n;}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state));},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e);};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var i;t&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,t));},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const{local:e,remote:i}=t.getSelectedCandidatePair();jC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})," )"));}}));}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null));}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack);}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),bn(s=e._hints).call(s,jA.LOW_STREAM)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async e=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}async getRemoteSSRC(e,t){var i,n;if(t=null!==(i=t)&&void 0!==i?i:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var r;const i=null===(r=JU.parse(t).mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===r?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId;}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),bn(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate());}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n);}};function jx(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(jC.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r);}o.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]));},n.stopCapture=Tb(()=>n.startCapture&&n.startCapture(),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),jC.debug("clean low stream renderer");},c;}var Wx,Hx,Kx,Yx,qx,zx,Jx,Xx,Qx,Zx,$x;DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"establish",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"connect",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"receive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,Array,String,String]),PI("design:returntype",cg)],Bx.prototype,"mockReceive",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"stopReceiving",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],Bx.prototype,"restartICE",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],Bx.prototype,"close",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateEncoderConfig",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[String,lb]),PI("design:returntype",cg)],Bx.prototype,"updateSendParameters",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[lb,String]),PI("design:returntype",cg)],Bx.prototype,"replaceTrack",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"muteLocal",null),DI([jx,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],Bx.prototype,"unmuteLocal",null),function(e){e[e.HEIGHT=2033]="HEIGHT",e[e.FRAME_RATE=2034]="FRAME_RATE",e[e.WIDTH=2035]="WIDTH";}(Wx||(Wx={})),function(e){e[e.HEIGHT=2072]="HEIGHT",e[e.FRAME_RATE=2074]="FRAME_RATE",e[e.WIDTH=2076]="WIDTH";}(Hx||(Hx={})),function(e){e[e.FRAME_RATE=2002]="FRAME_RATE",e[e.WIDTH=2003]="WIDTH",e[e.HEIGHT=2004]="HEIGHT",e[e.PACKAGE_LOST=2005]="PACKAGE_LOST",e[e.AVG_ENCODE=2007]="AVG_ENCODE",e[e.NACKS=2009]="NACKS",e[e.PLIS=2010]="PLIS",e[e.FIRS=2011]="FIRS",e[e.BITRATE=2012]="BITRATE",e[e.PACKAGE_RATE=2031]="PACKAGE_RATE",e[e.ADAPTATION=2032]="ADAPTATION",e[e.ACTUAL_ENCODED=2060]="ACTUAL_ENCODED",e[e.BANDWIDTH=2061]="BANDWIDTH",e[e.RETRANSMIT=2062]="RETRANSMIT",e[e.TARGET_ENCODED=2064]="TARGET_ENCODED",e[e.TRANSMIT=2066]="TRANSMIT",e[e.FREEZE=2082]="FREEZE",e[e.DISABLED=2095]="DISABLED",e[e.PLAYER_STATUS=2128]="PLAYER_STATUS",e[e.QP_SUM=2143]="QP_SUM";}(Kx||(Kx={})),function(e){e[e.BITRATE=2069]="BITRATE",e[e.PACKAGE_LOST=2070]="PACKAGE_LOST",e[e.PACKAGE_RATE=2071]="PACKAGE_RATE",e[e.HEIGHT=2073]="HEIGHT",e[e.FRAME_RATE=2075]="FRAME_RATE",e[e.WIDTH=2077]="WIDTH";}(Yx||(Yx={})),function(e){e[e.JITTER=-1]="JITTER",e[e.PACKAGE_LOST=2014]="PACKAGE_LOST",e[e.WIDTH=2018]="WIDTH",e[e.HEIGHT=2019]="HEIGHT",e[e.FRAME_RATE=2020]="FRAME_RATE",e[e.JITTER_BUFFER=2023]="JITTER_BUFFER",e[e.CURRENT_DELAY=2024]="CURRENT_DELAY",e[e.NACKS=2026]="NACKS",e[e.PLIS=2027]="PLIS",e[e.FIRS=2028]="FIRS",e[e.BITRATE=2029]="BITRATE",e[e.PACKAGE_RATE=2078]="PACKAGE_RATE",e[e.FREEZE=2084]="FREEZE",e[e.DISABLED=2101]="DISABLED",e[e.PLAYER_STATUS=2129]="PLAYER_STATUS",e[e.QP_SUM=2144]="QP_SUM",e[e.I_FRAME_DELAY=2149]="I_FRAME_DELAY";}(qx||(qx={})),function(e){e[e.FRAME_RATE_DECODE=2021]="FRAME_RATE_DECODE",e[e.FRAME_RATE_RENDER=2022]="FRAME_RATE_RENDER",e[e.FREEZE_TIME=2109]="FREEZE_TIME",e[e.FREEZE_TIME_RENDER=2147]="FREEZE_TIME_RENDER";}(zx||(zx={})),function(e){e[e.PCM_LEVEL=2104]="PCM_LEVEL";}(Jx||(Jx={})),function(e){e[e.PACKAGE_LOST=-1]="PACKAGE_LOST",e[e.LEVEL=2038]="LEVEL",e[e.BITRATE=2039]="BITRATE",e[e.PACKAGE_RATE=2040]="PACKAGE_RATE",e[e.AEC_RETURN_LOSS=2041]="AEC_RETURN_LOSS",e[e.AEC_RETURN_LOSS_ENH=2042]="AEC_RETURN_LOSS_ENH",e[e.FREEZE=2081]="FREEZE",e[e.DISABLED=2096]="DISABLED";}(Xx||(Xx={})),function(e){e[e.BITRATE=2044]="BITRATE",e[e.PACKAGE_LOST=2045]="PACKAGE_LOST",e[e.PACKAGE_RATE=2046]="PACKAGE_RATE",e[e.CURRENT_DELAY=2047]="CURRENT_DELAY",e[e.JITTER_BUFFER=2054]="JITTER_BUFFER",e[e.JITTER=2055]="JITTER",e[e.FREEZE=2083]="FREEZE",e[e.DISABLED=2102]="DISABLED",e[e.PCM_LEVEL=2105]="PCM_LEVEL",e[e.PLAYER_STATUS=2130]="PLAYER_STATUS",e[e.CONCEALED_SAMPLES=2148]="CONCEALED_SAMPLES";}(Qx||(Qx={})),function(e){e[e.FREEZE_TIME=-1]="FREEZE_TIME",e[e.LEVEL=2043]="LEVEL";}(Zx||(Zx={})),function(e){e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE";}($x||($x={}));const eV=1e3,tV=3;function iV(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)));}function nV(e){const t={[$x.CONN_TYPE]:0,[$x.RTT]:e.rtt};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[$x.CONN_TYPE]=1),"tcp"===i&&(t[$x.CONN_TYPE]=3),"tls"===i&&(t[$x.CONN_TYPE]=4);break;}case"srflx":t[$x.CONN_TYPE]=2;}return t;}class rV extends dT{constructor(e){super(),sh(this,"store",void 0),sh(this,"uploadWRTCStatsTimer",void 0),sh(this,"uploadOutboundDenoiserStatsTimer",void 0),sh(this,"uploadExtStatsTimer",void 0),sh(this,"uploadExtUsageStatsTimer",void 0),sh(this,"uploadInboundExtStatsTimer",void 0),sh(this,"requestStats",void 0),sh(this,"requestTransportStats",void 0),sh(this,"requestLocalMedia",void 0),sh(this,"requestRemoteMedia",void 0),sh(this,"requestAllTracks",void 0),sh(this,"requestVideoIsReady",void 0),sh(this,"requestUploadStats",void 0),sh(this,"requestUpload",void 0),sh(this,"uploadOutboundStarted",!1),sh(this,"uploadInboundStarted",!1),sh(this,"uploadTransportStarted",!1),sh(this,"uploadExtensionUsageStarted",!1),sh(this,"lastRecvStats",void 0),sh(this,"lastSendStats",void 0),sh(this,"lastFullRecvStats",void 0),sh(this,"lastFullSendStats",void 0),sh(this,"needUploadRenderFreezeTime",!0),this.store=e;}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;let t,i;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){const n={};if(this.uploadTransportStarted&&t){const r=this.getTransportStats(t,i,e);r&&(n.misc=[r]);}if(this.uploadOutboundStarted&&t){const i=this.getOutboundStats(t,e?this.lastSendStats:this.lastFullSendStats,e);i&&(n.outbound=[i]);}if(this.uploadInboundStarted&&i){const t=this.getInboundStats(i,e?this.lastRecvStats:this.lastFullRecvStats,e);t&&(n.inbound=t);}this.requestUploadStats(n);}this.lastRecvStats=i,this.lastSendStats=t,e||(this.lastFullRecvStats=i,this.lastFullSendStats=t);}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;let e=1;this.uploadWRTCStatsTimer=window.setInterval(()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted)return this.stopUploadWRTCStats();this.uploadWRTCStats(e!==tV),++e===tV+1&&(e=1);},eV);}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0);}getTransportStats(e,t,i){if(!this.requestStats)return;if(i)return null==e.rtt?void 0:{addition:{[$x.RTT]:e.rtt,[$x.CONN_TYPE]:void 0}};const n=nV(e);if(this.store.useP2P){if(t){const e=nV(t);n[$x.CONN_TYPE]+=e[$x.CONN_TYPE]<<3;}n[$x.CONN_TYPE]+=110;}else n[$x.CONN_TYPE]+=100;return {addition:n};}getOutboundStats(e,t,i){if(!this.requestUploadStats||!this.requestLocalMedia)return;const n=this.requestLocalMedia();if(!n||0===n.length)return;let r,s,o;return n.forEach(n=>{let[a,{track:c,ssrcs:d}]=n;switch(a){case lv.LocalVideoLowTrack:case lv.LocalVideoTrack:if(a===lv.LocalVideoTrack){const n=function(e,t,i,n,r){const s=t.videoSend.find(t=>t.ssrc===e);if(!s)return;const o={},{sentFrame:a,inputFrame:c}=s;if(c&&a){const e=c.frameRate,t=a.frameRate;o[Kx.FREEZE]=function(e,t){let i=!0;return i=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),i;}(e,t)?1:0;}if(iV(o,Kx.QP_SUM,s.qpSumPerFrame),r)return o;switch(a&&(iV(o,Kx.HEIGHT,a.height),iV(o,Kx.WIDTH,a.width),iV(o,Kx.FRAME_RATE,a.frameRate)),o[Kx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":o[Kx.ADAPTATION]=0;break;case"cpu":o[Kx.ADAPTATION]=1;break;case"bandwidth":o[Kx.ADAPTATION]=2;break;case"other":o[Kx.ADAPTATION]=3;}o[Kx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],iV(o,Kx.NACKS,s.nacksCount),iV(o,Kx.PLIS,s.plisCount),iV(o,Kx.FIRS,s.firsCount),iV(o,Kx.AVG_ENCODE,s.avgEncodeMs);const d=i&&i.videoSend.find(t=>t.ssrc===e);if(d){let e=r?eV:eV*tV;d.timestamp&&s.timestamp&&(e=s.timestamp-d.timestamp),null!=d.packets&&null!=s.packets&&iV(o,Kx.PACKAGE_RATE,1e3*(s.packets-d.packets)/e),null!=s.packetsLost&&null!=d.packetsLost&&iV(o,Kx.PACKAGE_LOST,s.packetsLost-d.packetsLost),null!=d.bytes&&null!=s.bytes&&iV(o,Kx.BITRATE,8*(s.bytes-d.bytes)/e);}return o;}(d[0].ssrcId,e,t,c,i),r=i?null:function(e,t,i){const n=t.videoSend.find(t=>t.ssrc===e);if(!n)return null;const r={},s=n.inputFrame,o=s&&s.height||i&&i._videoHeight||0,a=s&&s.width||i&&i._videoWidth||0,c=s&&s.frameRate||0;return iV(r,Wx.HEIGHT,o),iV(r,Wx.WIDTH,a),iV(r,Wx.FRAME_RATE,c),r;}(d[0].ssrcId,e,c),o=i?null:function(e){const t={};return iV(t,Kx.RETRANSMIT,e.bitrate.retransmit),iV(t,Kx.TARGET_ENCODED,e.bitrate.targetEncoded),iV(t,Kx.ACTUAL_ENCODED,e.bitrate.actualEncoded),iV(t,Kx.TRANSMIT,e.bitrate.transmit),iV(t,Kx.BANDWIDTH,e.sendBandwidth),t;}(e);s=Object.assign({},n,r,o);}else o=i?void 0:function(e,t,i){const n=t.videoSend.find(t=>t.ssrc===e);if(!n)return;const r={},s=n.sentFrame;if(s&&(iV(r,Yx.HEIGHT,s.height),iV(r,Yx.WIDTH,s.width),iV(r,Yx.FRAME_RATE,s.frameRate)),i){const t=i.videoSend.find(t=>t.ssrc===e);if(t){let e=eV*tV;t.timestamp&&n.timestamp&&(e=n.timestamp-t.timestamp),null!=t.packets&&null!=n.packets&&iV(r,Yx.PACKAGE_RATE,1e3*(n.packets-t.packets)/e),null!=n.packetsLost&&null!=t.packetsLost&&iV(r,Yx.PACKAGE_LOST,n.packetsLost-t.packetsLost),null!=t.bytes&&null!=n.bytes&&iV(r,Yx.BITRATE,8*(n.bytes-t.bytes)/e);}}return r;}(d[0].ssrcId,e,t);break;case lv.LocalAudioTrack:r=i?void 0:function(e,t,i,n){const r=t.audioSend.find(t=>t.ssrc===e);if(!r)return;const s={};s[Xx.DISABLED]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const o=n._source.getAccurateVolumeLevel(),a=r.inputLevel;iV(s,Xx.LEVEL,100*(null==a?o:a)),iV(s,Jx.PCM_LEVEL,100*o),iV(s,Xx.AEC_RETURN_LOSS,r.aecReturnLoss),iV(s,Xx.AEC_RETURN_LOSS_ENH,r.aecReturnLossEnhancement),s[Xx.FREEZE]=0;const c=i&&i.audioSend.find(t=>t.ssrc===e);if(c){let e=eV*tV;c.timestamp&&r.timestamp&&(e=r.timestamp-c.timestamp),null!=c.bytes&&null!=r.bytes&&iV(s,Xx.BITRATE,8*(r.bytes-c.bytes)/e),null!=c.packets&&null!=r.packets&&iV(s,Xx.PACKAGE_RATE,1e3*(r.packets-c.packets)/e);}return s;}(d[0].ssrcId,e,t,c);}}),{high:s,low:o,audio:r};}getInboundStats(e,t,i){if(!this.requestRemoteMedia)return;const n=this.requestRemoteMedia()||[],r=[];return n.forEach(n=>{let[s,o]=n;const a={peer:s.uid};if(o.has(av.VIDEO)&&s.videoTrack){const n=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,r=s.videoTrack?function(e,t,i,n,r,s,o){const a=t.videoRecv.find(t=>t.ssrc===e);if(!a)return;const c={},{receivedFrame:d,outputFrame:l,decodeFrameRate:u}=a,h=i&&i.videoRecv.find(t=>t.ssrc===e);if(c[qx.FREEZE]=r&&mV.isRemoteVideoFreeze(n,a,h)?1:0,iV(c,zx.FRAME_RATE_DECODE,u),iV(c,qx.QP_SUM,a.qpSumPerFrame),a.framesRateFirefox&&iV(c,qx.FRAME_RATE,a.framesRateFirefox),d&&iV(c,qx.FRAME_RATE,d.frameRate),h){const e=t.timestamp-i.timestamp||(o?eV:tV*eV);null!=a.packetsLost&&null!=h.packetsLost&&iV(c,qx.PACKAGE_LOST,a.packetsLost-h.packetsLost),null!=h.bytes&&null!=a.bytes&&iV(c,qx.BITRATE,8*(a.bytes-h.bytes)/e),null!=h.packets&&null!=a.packets&&iV(c,qx.PACKAGE_RATE,1e3*(a.packets-h.packets)/e);}if(o)return c;if(d?(iV(c,qx.HEIGHT,d.height),iV(c,qx.WIDTH,d.width)):n&&(iV(c,qx.HEIGHT,n._videoHeight||0),iV(c,qx.WIDTH,n._videoWidth||0)),l&&iV(c,zx.FRAME_RATE_RENDER,l.frameRate),iV(c,qx.JITTER_BUFFER,a.jitterBufferMs),iV(c,qx.CURRENT_DELAY,a.currentDelayMs),iV(c,qx.FIRS,a.firsCount),iV(c,qx.NACKS,a.nacksCount),iV(c,qx.PLIS,a.plisCount),n){c[qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const{freezeTimeCounterList:t,renderFreezeAccTime:i}=e;if(t&&t.length>0&&iV(c,zx.FREEZE_TIME,t.splice(0,1)[0]),s&&"visible"===Dw.visibility){const t=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-t),iV(c,zx.FREEZE_TIME_RENDER,t);}}}if(c[qx.PLAYER_STATUS]=ab[n._player?n._player.videoElementStatus:"uninit"],h&&void 0!==a.totalInterFrameDelay&&void 0!==a.totalSquaredInterFrameDelay&&void 0!==h.totalInterFrameDelay&&void 0!==h.totalSquaredInterFrameDelay){const e=a.totalInterFrameDelay-h.totalInterFrameDelay,t=a.totalSquaredInterFrameDelay-h.totalSquaredInterFrameDelay,i=a.framesDecodeCount-h.framesDecodeCount,n=e/i*1e3,r=Math.round(1e3*Math.sqrt((t-Math.pow(e,2)/i)/i));!isNaN(r)&&n+r>Math.max(3*n,n+150)&&(c[qx.I_FRAME_DELAY]=r);}return c;}(s._videoSSRC,e,t,s.videoTrack,!0===n,this.needUploadRenderFreezeTime,i):void 0;r&&(a.video=r);}if(o.has(av.AUDIO)&&s.audioTrack){const n=s.audioTrack?function(e,t,i,n,r){const s=t.audioRecv.find(t=>t.ssrc===e);if(!s)return;const o={},a=i&&i.audioRecv.find(t=>t.ssrc===e),{receivedFrames:c,droppedFrames:d}=s;var l,u;if(iV(o,Qx.JITTER,s.jitterMs),null!=c&&null!=d&&(o[Qx.FREEZE]=(u=d,0===(l=c)||100*u/l>20?1:0)),a){const e=t.timestamp-i.timestamp||(r?eV:eV*tV);null!=s.packets&&null!=a.packets&&iV(o,Qx.PACKAGE_RATE,1e3*(s.packets-a.packets)/e),null!=a.bytes&&null!=s.bytes&&iV(o,Qx.BITRATE,8*(s.bytes-a.bytes)/e),null!=s.packetsLost&&null!=a.packetsLost&&iV(o,Qx.PACKAGE_LOST,s.packetsLost-a.packetsLost);}if(r)return o;const h=n._source.getAccurateVolumeLevel(),p=s.outputLevel;if(iV(o,Zx.LEVEL,100*(null==p?h:p)),iV(o,Qx.PCM_LEVEL,100*h),n&&(o[Qx.DISABLED]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),iV(o,Qx.JITTER_BUFFER,s.jitterBufferMs),iV(o,Qx.CURRENT_DELAY,s.jitterBufferMs),o[Qx.PLAYER_STATUS]=ab[Gb.getPlayerState(n.getTrackId())],a){const e=s.concealedSamples-a.concealedSamples;e>0&&iV(o,Qx.CONCEALED_SAMPLES,e);}return o;}(s._audioSSRC,e,t,s.audioTrack,i):void 0;n&&(a.audio=n);}(a.video||a.audio)&&r.push(a);}),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,r;}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats();}stopUploadTransportStats(){this.uploadTransportStarted=!1;}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find(e=>e instanceof tw);if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(mI.DENOISER_STATS,t);}},2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach(e=>{e.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});});},2e3));}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0);}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval(()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach(e=>{let[t,i]=e;if(i.has(av.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});}if(i.has(av.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats);});}});},2e3));}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0));}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map();this.uploadExtUsageStatsTimer=window.setInterval(async()=>{const t=Date.now(),i={connectionInterval:RC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let n=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(n=n.concat(await e.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[e,t]of s)t.has(av.VIDEO)&&e.videoTrack&&(n=n.concat(await e.videoTrack.getProcessorUsage())),t.has(av.AUDIO)&&e.audioTrack&&(n=n.concat(await e.audioTrack.getProcessorUsage()));if(0===n.length)return;i.details=function(e,t){const i={};for(const{id:o,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(o))&&void 0!==n?n:0,l=2===a?e+RC("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,s;t.set(o,l),i[o]?(2===a&&(i[o].value=a),c>i[o].level&&(i[o].level=c),"remote"===d&&(i[o].remoteUidCount+=1),i[o].totalTs=null!==(r=t.get(o))&&void 0!==r?r:0):i[o]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(s=t.get(o))&&void 0!==s?s:0};}return Object.keys(i).map(e=>{const{level:t,value:n,totalTs:r}=i[e];return {id:e,level:t,value:n,totalTs:r};});}(n,e);const o=Date.now(),a=o>t?o:t+1;this.requestUpload&&this.requestUpload(mI.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:a});},RC("EXTENSION_USAGE_UPLOAD_INTERVAL"));}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0);}}class sV{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_;}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_;}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack;}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack;}get dataChannels(){return this._dataChannels;}constructor(e,t){sh(this,"uid",void 0),sh(this,"_uintid",void 0),sh(this,"_trust_in_room_",!0),sh(this,"_trust_audio_enabled_state_",!0),sh(this,"_trust_video_enabled_state_",!0),sh(this,"_trust_audio_mute_state_",!0),sh(this,"_trust_video_mute_state_",!0),sh(this,"_audio_muted_",!1),sh(this,"_video_muted_",!1),sh(this,"_audio_enabled_",!0),sh(this,"_video_enabled_",!0),sh(this,"_audio_added_",!1),sh(this,"_video_added_",!1),sh(this,"_is_pre_created",!1),sh(this,"_video_pre_subscribed",!1),sh(this,"_audio_pre_subscribed",!1),sh(this,"_trust_video_stream_added_state_",!0),sh(this,"_trust_audio_stream_added_state_",!0),sh(this,"_audioTrack",void 0),sh(this,"_videoTrack",void 0),sh(this,"_dataChannels",[]),sh(this,"_audioSSRC",void 0),sh(this,"_videoSSRC",void 0),sh(this,"_audioOrtc",void 0),sh(this,"_videoOrtc",void 0),sh(this,"_cname",void 0),sh(this,"_rtxSsrcId",void 0),sh(this,"_videoMid",void 0),sh(this,"_audioMid",void 0),this.uid=e,this._uintid=t;}}var oV;function aV(e,t){var i;let n;switch(t){case lv.LocalAudioTrack:n=JI.Audio;break;case lv.LocalVideoTrack:n=bn(i=e._hints).call(i,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:n=JI.Low;}return n;}function cV(e){const t=IA();if(e.some(e=>e._bypassWebAudio))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing");}function dV(e,t){cV(e);const i=t||new nw();return e.forEach(e=>i.addAudioTrack(e)),i;}function lV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function uV(e){for(var t=1;t{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const o=this.filterTobeMutedTracks(e);if(0===o.length)return void t();const a=o.find(e=>"videoLowTrack"===e[0]);if(a){a[1].track._originMediaStreamTrack.stop();}await this.sendConnection.muteLocal(o.map(e=>{let[,{id:t}]=e;return t;}));let c=!1;var r,s;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(lv.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.id);const d=this.createMuteMessage(o);await yT(this,hv.RequestMuteLocal,d);const l="video"===e.trackMediaType?Av.MUTE_LOCAL_VIDEO:Av.MUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const s=this.createUnmuteMessage(r),o="video"===e.trackMediaType?Av.UNMUTE_LOCAL_VIDEO:Av.UNMUTE_LOCAL_AUDIO;await yT(this,hv.RequestP2PMuteLocal,{action:o,message:s}),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s),await this.sendConnection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.sendMutex.lock("Locking from P2PChannel2.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;r&&(await this.sendConnection.updateSendParameters(r,s)),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!this.sendConnection||!i||void 0===i[1].id||this.state!==uv.Connected)return void t();if(await(null===(s=this.sendConnection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),i[0]===lv.LocalVideoTrack&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(e),this.bindStatsUploaderEvents(),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));});},RC("ICE_RESTART_INTERVAL"));}async startP2PConnection(e,t){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.");}async connect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support connect.");}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Bx(e,this.store,TI.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=await this.recvConnection.establish(t);return {iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp};}{this.state=uv.New,this.sendConnection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Bx(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return {iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp};}}finally{i&&i();}}async p2pConnect(e){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected;}async addRemoteCandidate(e,t){if(t===TI.RECEIVE_ONLY){if(!this.sendConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e);}else {if(!this.recvConnection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e);}}publish(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==uv.Connected){n.throwIfTrackTypeNotMatch(e);const t=e.filter(e=>-1===n.pendingLocalTracks.indexOf(e));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t));}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",r);}),n.bindLocalTrackEvents(s);const o=yield IU(n.sendConnection.send(s.map(e=>{let{track:t}=e;return t;}),n.store.codec,n.store.audioCodec)),a=(yield IU(o.next())).value,c=n.createGatewayPublishMessage(s,a);try{yield c;}catch(e){throw o.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&s.forEach(e=>{let{track:t}=e;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t);}),n.unbindLocalTrackEvents(s),e;}yield IU(o.next()),s.forEach(e=>{let{type:t}=e;n.statsCollector.addLocalStats(t);}),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(s,a),s.forEach(e=>{let{track:t,type:i}=e;const r=Date.now();n.store.publish(t.getTrackId(),i===lv.LocalAudioTrack?"audio":"video",void 0,r);}),n.startUploadUplinkState();}finally{r();}})();}async unpublish(e){if(!this.sendConnection||this.state!==uv.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(t=>!bn(e).call(e,t)));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find(e=>"videoLowTrack"===e[0]);if(i){i[1].track.close();}const n=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return {type:t,track:i};})),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t);}),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===uv.Connected){if(i){i[1].track.close();}return n;}e.forEach(e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1);});}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach(i=>{let[n,{track:r,ssrcs:s}]=i;const o={stream_type:aV(r,n),ssrcs:s};r._muted||!r._enabled?e.push(o):t.push(o);}),e.length>0&&e.forEach(e=>{yT(this,hv.RequestMuteLocal,[e]);}),t.length>0&&t.forEach(e=>{yT(this,hv.RequestUnmuteLocal,[e]);});};e(),this.uplinkStateUploadInterval=window.setInterval(()=>{e();},3e3);}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval));}publishLowStream(e){return PU(function*(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support publishLowStream.");})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]);}async unpublishLowStream(){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.");}async subscribe(e,t,i,n){var r;if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const{track:s,mid:o,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),n);t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Nw(s,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new Ow(s,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,o):this.remoteUserMap.set(e,new Map([[t,o]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex(i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r;});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,e.uid));}async mockSubscribe(e,t,i,n){if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),n);}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter(i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid;});if(n.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),this.recvConnection||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0;}}),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach(e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.recvConnection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),r.forEach(e=>{let[,{kind:t}]=e;yT(this,hv.RequestP2PMuteRemote,t);}));}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach(e=>{let[,t]=e;[av.VIDEO,av.AUDIO].forEach(e=>{t.has(e)?yT(this,hv.RequestP2PUnmuteRemote,e):yT(this,hv.RequestP2PMuteRemote,e);});});e(),this.downlinkStatsUploadInterval=window.setInterval(()=>{e();},3e3);}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval));}getAllDataChannels(){return this.localDataChannels;}async massSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribe.");}async massSubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.");}async massUnsubscribe(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.");}async massUnsubscribeNoLock(e){throw new Kg(Hg.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.");}async muteRemote(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1);}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t);}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;}).concat(i.trackList);}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;});}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new pS("P2PChannel2-send-mutex"),this.sendMutex=new pS("P2PChannel2-recv-mutex"),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e);});}e.track.close();}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=uv.Disconnected;}getStats(e){var t,i;return e?null===(i=this.recvConnection)||void 0===i?void 0:i.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats();}getRemoteVideoIsReady(e){var t;return (null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1;}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return {width:e.track._videoWidth||0,height:e.track._videoHeight||0};}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0;}getLocalMedia(e){return this.localTrackMap.get(e);}hasLocalMedia(){return this.localTrackMap.size>0;}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{};}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return {uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0};});const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop());}),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.MediaReconnectStart,t.uid);}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")));}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return !0;}return !1;}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t});}async restartICE(e,t){let i,n;if(e===TI.SEND_ONLY){if(!this.sendConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection;}else {if(!this.recvConnection)throw new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection;}try{if(t){const e=await n.restartICE(t);return n.isInRestartIce=!1,e;}{const e=await n.restartICE();if(e){const t=await vT(this,hv.RequestP2PRestartICE,{direction:TI.RECEIVE_ONLY,iceParameter:e});await n.restartICE(t),n.isInRestartIce=!1;}}}finally{i();}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find(e=>{var i;return e.ssrc===(null==t||null===(i=t.ssrcs)||void 0===i?void 0:i[0].ssrcId);}),r=e.audioSend.find(e=>{var t;return e.ssrc===(null==i||null===(t=i.ssrcs)||void 0===t?void 0:t[0].ssrcId);});if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5;}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t;}async muteLocalTrack(e){return new cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}filterTobePublishedTracks(e,t,i){const n=[],r=IA(),s=this.getAllTracks();e=HT(e=e.filter(e=>-1===s.indexOf(e)));let o=!1,a=!1;for(const s of e){if(s instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:s,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(s,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(s instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e){if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s),this.bindLocalAudioTrackEvents(s,!0);}else if(a){const e=n.find(e=>{let{type:t}=e;return t===lv.LocalAudioTrack;});if(!(e.track instanceof nw))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(s._bypassWebAudio)throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(s);}else {if(!r.webAudioMediaStreamDest||s instanceof nw||s._bypassWebAudio)n.push({track:s,type:lv.LocalAudioTrack});else {const e=new nw();e.addAudioTrack(s),n.push({track:e,type:lv.LocalAudioTrack});}a=!0;}}}return n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack));}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return {track:i,type:t};})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,{track:s,type:o}=e;switch(o){case lv.LocalAudioTrack:r=JI.Audio;break;case lv.LocalVideoTrack:r=bn(n=s._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:r=JI.Low;}return {kind:o===lv.LocalAudioTrack?av.AUDIO:av.VIDEO,stream_type:r,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:s.muted||!s.enabled};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC});});}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t);});}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(hv.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),bn(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&(await iS(800)),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction));},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i);},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);},e.onLocalCandidate=t=>{this.emit(hv.LocalCandidate,{candidate:t,direction:e.direction});};}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0;}async handleDisconnect(e){const t=e===TI.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,jC.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===TI.SEND_ONLY?this.restartICE(e):vT(this,hv.RequestP2PRestartICE,{direction:TI.SEND_ONLY}));}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}]);}else Array.from(n.entries()).forEach(t=>{let[n,r]=t;i.push([e,{kind:n,id:r}]);});return i;}createUnsubscribeMessage(e){const t=[];return e.forEach(e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}));}}),t;}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t));});}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink)),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}));}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return "connected"!==e&&"connected"!==t;}return !0;}async tryToUnmuteAudio(e){for(let t=0;tthis.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(e=>{let[,{ssrcs:t}]=e;return !!t;}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return !(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e));},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks();}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0;}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");}}getLowVideoTrack(e,t){const i=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=uV(uV({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,uV(uV({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock");}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0});}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return !1;const n=this.remoteUserMap.get(e);if(!n)return !1;const r=n.get(t);if(!r)return !1;const s=await this.recvConnection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel2] reset connection to ").concat(e)),this.state===uv.Connected?(jC.debug("[".concat(this.store.clientId,"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first")),this.disconnectForReconnect()):(this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0));}async publishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED);}async unpublishDataChannel(e){throw new Kg(Hg.NOT_SUPPORTED);}async subscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async unsubscribeDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}hasPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}setPendingRemoteDataChannel(e,t){throw new Kg(Hg.NOT_SUPPORTED);}async preConnect(e,t,i,n,r,s){throw new Kg(Hg.NOT_SUPPORTED);}getEstablishParams(){throw new Kg(Hg.NOT_SUPPORTED);}async reSubscribe(e){throw new Kg(Hg.NOT_SUPPORTED);}async updateVideoStreamParameter(e,t){throw new Kg(Hg.NOT_SUPPORTED);}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}}function pV(e){return function(t,i,n){const r=t[i];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return n.value=async function(){for(var t=arguments.length,n=new Array(t),s=0;s{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel));}),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new TU(),this.exceptionMonitor.on("exception",(e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i);});}reset(){this.localStats=new Map(),this.remoteStats=new Map(),this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0;}getLocalAudioTrackStats(){return this.localStats.get(lv.LocalAudioTrack)||EV({},XA);}getLocalVideoTrackStats(){return this.localStats.get(lv.LocalVideoTrack)||EV({},QA);}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t;},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r));}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r));});return i;}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n);}else Array.from(this.remoteStats.entries()).forEach(e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n);});return t;}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t;},i={};if(e){var n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r));}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r));});return i;}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(lv.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const s=this.localStats.get(lv.LocalVideoTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate);const o=this.localStats.get(lv.LocalVideoLowTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate),this.remoteStats.forEach(e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate);});let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0};}addLocalStats(e){this.localStats.set(e,void 0);}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear();}addRemoteStats(e){this.remoteStats.set(e,{});}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear();}addP2PChannel(e){this.p2pChannel=e;}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter(e=>void 0!==e.B_ppad||void 0!==e.B_ppvd);e.peer_delay.filter(e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid)).forEach(e=>{var t;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?RU.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid));}),this.trafficStats=e;}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&jC.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e;}static isRemoteVideoFreeze(e,t,i){if(!e)return !1;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r;}static isRemoteAudioFreeze(e){return !!e&&e._isFreeze();}isLocalVideoFreeze(e){return !(!e.inputFrame||!e.sentFrame)&&e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3;}updateLocalStats(e){Array.from(this.localStats.entries()).forEach(t=>{let[i,n]=t;switch(i){case lv.LocalVideoTrack:case lv.LocalVideoLowTrack:{const t=n,s=EV({},QA),o=e.getStats(),a=e.getLocalMedia(i);if(o){const i=o.videoSend.find(e=>e.ssrc===(null==a?void 0:a.ssrcs[0].ssrcId));if(i){const n=e.getLocalVideoSize(),r=e.getEncoderConfig(lv.LocalVideoTrack);"H264"!==i.codec&&"H265"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(s.codecType=i.codec),s.sendBytes=i.bytes,s.sendBitrate=t?8*Math.max(0,s.sendBytes-t.sendBytes):0,i.inputFrame?(s.captureFrameRate=i.inputFrame.frameRate,s.captureResolutionHeight=i.inputFrame.height,s.captureResolutionWidth=i.inputFrame.width):n&&(s.captureResolutionWidth=n.width,s.captureResolutionHeight=n.height),i.sentFrame?(s.sendFrameRate=i.sentFrame.frameRate,s.sendResolutionHeight=i.sentFrame.height,s.sendResolutionWidth=i.sentFrame.width):n&&(s.sendResolutionWidth=n.width,s.sendResolutionHeight=n.height),i.avgEncodeMs&&(s.encodeDelay=i.avgEncodeMs),r&&r.bitrateMax&&(s.targetSendBitrate=1e3*r.bitrateMax),s.sendPackets=i.packets,s.sendPacketsLost=i.packetsLost,s.sendJitterMs=i.jitterMs,s.sendRttMs=i.rttMs,s.totalDuration=t?t.totalDuration+1:1,s.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(s.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(jC.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode);}this.trafficStats&&(s.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100);}var r;if(this.localStats.set(i,s),(null==t?void 0:t.sendResolutionWidth)!==s.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==s.sendResolutionHeight)null===(r=this.onStatsChanged)||void 0===r||r.call(this,"resolution",{width:s.sendResolutionWidth,height:s.sendResolutionHeight});s&&a&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,a.track,s);break;}case lv.LocalAudioTrack:{const t=n,r=EV({},XA),s=e.getStats(),o=e.getLocalMedia(i);if(s){const i=s.audioSend.find(e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else {const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t));}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendJitterMs=i.jitterMs,r.sendRttMs=i.rttMs,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0;}}this.trafficStats&&(r.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(lv.LocalAudioTrack,r),r&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,r);break;}}});}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{var i,n;let[r,{videoStats:s,audioStats:o,videoPcStats:a}]=t;const c=o,d=s,l=a,u=EV({},ZA),h=EV({},eb),p=EV({},$A),{audioTrack:_,videoTrack:E,audioSSRC:m,videoSSRC:f}=e.getRemoteMedia(r);let g;g=e instanceof hV?e.getStats(!0):e.getStats();const T=null===(i=g)||void 0===i?void 0:i.audioRecv.find(e=>e.ssrc===m),S=null===(n=g)||void 0===n?void 0:n.videoRecv.find(e=>e.ssrc===f),R=this.trafficStats&&this.trafficStats.peer_delay.find(e=>e.peer_uid===r);if(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):_&&(u.receiveLevel=Math.round(32767*_.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&mV.isRemoteAudioFreeze(_)&&(u.totalFreezeTime+=1)),S){"H264"!==S.codec&&"H265"!==S.codec&&"VP8"!==S.codec&&"VP9"!==S.codec&&"AV1X"!==S.codec&&"AV1"!==S.codec||(h.codecType=S.codec),h.receiveBytes=S.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,h.renderFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,S.outputFrame&&(h.renderFrameRate=S.outputFrame.frameRate),S.receivedFrame?(h.receiveFrameRate=S.receivedFrame.frameRate,h.receiveResolutionHeight=S.receivedFrame.height,h.receiveResolutionWidth=S.receivedFrame.width):E&&(h.receiveResolutionHeight=E._videoHeight||0,h.receiveResolutionWidth=E._videoWidth||0),void 0!==S.framesRateFirefox&&(h.receiveFrameRate=Math.round(S.framesRateFirefox)),h.receivePackets=S.packets,h.receivePacketsLost=S.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.receiveDelay=S.jitterBufferMs||0;const t=!!f&&e.getRemoteVideoIsReady(f);E&&t&&mV.isRemoteVideoFreeze(E,S,l)&&(h.totalFreezeTime+=1),h.freezeRate=h.totalFreezeTime/h.totalDuration;}R&&(u.end2EndDelay=R.B_ad,h.end2EndDelay=R.B_vd,u.transportDelay=R.B_ed,h.transportDelay=R.B_ed,u.currentPacketLossRate=R.B_ealr4/100,h.currentPacketLossRate=R.B_evlr4/100,p.uplinkNetworkQuality=R.B_punq?R.B_punq:0,p.downlinkNetworkQuality=R.B_pdnq?R.B_pdnq:0),this.remoteStats.set(r,{audioStats:u,videoStats:h,videoPcStats:S,networkStats:p}),_&&this.exceptionMonitor.setRemoteAudioStats(_,u),E&&this.exceptionMonitor.setRemoteVideoStats(E,h);});}}function fV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function gV(e){for(var t=1;t{this.reconnectMode="retry",this.startPingPong();}),sh(this,"handleWebSocketMessage",e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):this.serviceMode===RI.INJECT?this.emit(jI.INJECT_STREAM_STATUS,t):(eI.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===RI.TRANSCODE?1:2}),this.emit(jI.PUBLISH_STREAM_STATUS,t));}),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new zv("live-streaming",i),this.websocket.on(SI.CONNECTED,this.handleWebSocketOpen),this.websocket.on(SI.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(SI.REQUEST_NEW_URLS,(e,t)=>{vT(this,jI.REQUEST_NEW_ADDRESS).then(e).catch(t);}),this.websocket.on(SI.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode;});}init(e){return this.websocket.init(e);}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new LI(Hg.UNEXPECTED_ERROR);const o=gV({command:e,sdkVersion:"4.20.2"===EC?"0.0.1":EC,seq:s,requestId:s,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new LI(Hg.WS_DISCONNECT);const a=()=>new cg((e,t)=>{this.websocket.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.websocket.once(SI.CONNECTED,e);});"connected"!==this.websocket.state&&(await a()),o.clientRequest&&(o.clientRequest.workerToken=this.token);const c=new cg((e,t)=>{const i=()=>{t(new LI(Hg.WS_ABORT));};this.websocket.once(SI.RECONNECTING,i),this.websocket.once(SI.CLOSED,i),this.once("@".concat(s,"-").concat(this.spec.sid),t=>{e(t);});});n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(o);let l=null;try{l=await c;}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i);}return n&&eI.workerEvent(this.spec.sid,gV(gV({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l;}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext");}close(){const e="4.20.2"===EC?"0.0.1":EC;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0);}handleResponseError(e){switch(e.code){case WI.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void jC.warning("live stream response already exists stream");case WI.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case WI.LIVE_STREAM_RESPONSE_BAD_STREAM:case WI.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new LI(Hg.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new LI(Hg.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new LI(Hg.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case WI.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new LI(Hg.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new LI(Hg.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(jI.WARNING,t,e.serverResponse.url);}case WI.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case WI.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new LI(Hg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw();}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(sS);},6e3);}}function SV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function RV(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:ES,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ES;super(),sh(this,"onLiveStreamWarning",void 0),sh(this,"onLiveStreamError",void 0),sh(this,"onInjectStatusChange",void 0),sh(this,"spec",void 0),sh(this,"retryTimeout",1e4),sh(this,"connection",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"wsRetryConfig",void 0),sh(this,"streamingTasks",new Map()),sh(this,"isStartingStreamingTask",!1),sh(this,"taskMutex",new pS("live-streaming")),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"transcodingConfig",void 0),sh(this,"injectConfig",RV({},BI)),sh(this,"injectLoopTimes",0),sh(this,"uapResponse",void 0),sh(this,"lastTaskId",1),sh(this,"statusError",new Map()),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t;}async setTranscodingConfig(e){const t=RV(RV({},FI),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(jC.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map(e=>RV(RV(RV({},UI),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),function(e){Zg(e.width)||zg(e.width,"config.width",0,1e4),Zg(e.height)||zg(e.height,"config.height",0,1e4),Zg(e.videoBitrate)||zg(e.videoBitrate,"config.videoBitrate",1,1e6),Zg(e.videoFrameRate)||zg(e.videoFrameRate,"config.videoFrameRate"),Zg(e.lowLatency)||Yg(e.lowLatency,"config.lowLatency"),Zg(e.audioSampleRate)||qg(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Zg(e.audioBitrate)||zg(e.audioBitrate,"config.audioBitrate",1,128),Zg(e.audioChannels)||qg(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Zg(e.videoGop)||zg(e.videoGop,"config.videoGop"),Zg(e.videoCodecProfile)||qg(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Zg(e.userCount)||zg(e.userCount,"config.userCount",0,17),Zg(e.backgroundColor)||zg(e.backgroundColor,"config.backgroundColor",0,16777215),Zg(e.userConfigExtraInfo)||Xg(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Zg(e.transcodingUsers)&&(Qg(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach((e,t)=>{MI(e.uid),Zg(e.x)||zg(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Zg(e.y)||zg(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Zg(e.width)||zg(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Zg(e.height)||zg(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Zg(e.zOrder)||zg(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Zg(e.alpha)||zg(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1);})),Zg(e.watermark)||VI(e.watermark,"watermark"),Zg(e.backgroundImage)||VI(e.backgroundImage,"backgroundImage"),e.images&&!Zg(e.images)&&(Qg(e.images,"config.images"),e.images.forEach((e,t)=>{VI(e,"images[".concat(t,"]"));}));}(t);const i=[];t.images&&i.push(...t.images.map(e=>RV(RV(RV({},xI),e),{},{zOrder:255}))),t.backgroundImage&&(i.push(RV(RV(RV({},xI),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(RV(RV(RV({},xI),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map(e=>RV({},e)),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map(e=>"number"==typeof e.uid?cg.resolve(e.uid):pA(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await cg.all(n)).forEach((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e);}),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(NI(r=this.streamingTasks).call(r)).map(e=>e.taskId).join("#")});jC.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig));}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(t=>{jC.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{jC.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"));}).catch(e=>{jC.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e);});});}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t;}async startLiveStreamingTask(e,t,i){var n;if(Array.from(NI(n=this.streamingTasks).call(n)).find(e=>e.mode===RI.INJECT)&&t===RI.INJECT)return new LI(Hg.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===RI.TRANSCODE)throw new LI(Hg.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};jC.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new LI(Hg.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t));}catch(e){throw s(),e;}switch(t){case RI.TRANSCODE:r.transcodingConfig=RV({},this.transcodingConfig);break;case RI.RAW:break;case RI.INJECT:r={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes};}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const n=new cg((t,n)=>{iS(this.retryTimeout).then(()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0;});}),a=await cg.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===RI.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),n]);this.isStartingStreamingTask=!1,jC.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),s();}catch(n){if(s(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n);}}stopLiveStreamingTask(e){return new cg((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new LI(Hg.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t();},this.connection.request("request",{clientRequest:{command:r===RI.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===RI.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{jC.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==RI.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===RI.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e);}).catch(i);});}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==RI.INJECT)throw new LI(Hg.INVALID_OPERATION,"can not find inject stream task to control");return (await this.connection.request("request",{clientRequest:{command:"ControlStream",url:e,control:t,audioVolume:i,position:n}})).serverResponse;}resetAllTask(){var e;const t=Array.from(NI(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch(t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t);});}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map(),this.isStartingStreamingTask=!1,this.statusError=new Map(),this.cancelToken=sC.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0;}async connect(e){if(this.connection)throw new LI(Hg.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new TV(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(jI.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(jI.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(jI.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(jI.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new LI(Hg.UNEXPECTED_ERROR,"can not get new live streaming address list"));vT(this,GI.REQUEST_WORKER_MANAGER_LIST,e).then(e=>{this.uapResponse=e,t(e.addressList);}).catch(i);}),await this.connection.init(t.addressList),this.connection;}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case WI.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case WI.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new LI(Hg.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return jC.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n);}case WI.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new LI(Hg.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e);}case WI.LIVE_STREAM_RESPONSE_WORKER_LOST:case WI.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(NI(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(jC.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new LI(Hg.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{jC.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url);}).catch(e=>{jC.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e);}));return;}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(CI.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void jC.debug("inject stream server status",e);}}hasUrl(e){return this.streamingTasks.has(e);}}class IV{constructor(){sh(this,"destChannelMediaInfos",new Map()),sh(this,"srcChannelMediaInfo",void 0);}setSrcChannelInfo(e){tv(e),this.srcChannelMediaInfo=e;}addDestChannelInfo(e){tv(e),this.destChannelMediaInfos.set(e.channelName,e);}removeDestChannelInfo(e){kI(e),this.destChannelMediaInfos.delete(e);}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo;}getDestChannelMediaInfo(){return this.destChannelMediaInfos;}}function vV(e){if(!(e instanceof IV)){return new LI(Hg.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new LI(Hg.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();}if(0===i.size){return new LI(Hg.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw();}}class yV extends dT{constructor(e,t,i){super(),sh(this,"ws",void 0),sh(this,"requestId",1),sh(this,"heartBeatTimer",void 0),sh(this,"joinInfo",void 0),sh(this,"clientId",void 0),sh(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck();}),sh(this,"onClose",e=>{this.emit("close"),this.dispose();}),sh(this,"onMessage",e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t);}),this.joinInfo=e,this.clientId=t,this.ws=new zv("cross-channel-".concat(this.clientId),i),this.ws.on(SI.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting");}),this.ws.on(SI.CONNECTED,this.onOpen),this.ws.on(SI.ON_MESSAGE,this.onMessage),this.ws.on(SI.CLOSED,this.onClose);}isConnect(){return "connected"===this.ws.state;}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t;}waitStatus(e){return new cg((t,i)=>{const n=window.setTimeout(()=>{i(new LI(Hg.TIMEOUT,"wait status timeout, status: ".concat(e)));},5e3);this.once(e,r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new LI(Hg.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0);}),this.once("dispose",()=>{window.clearTimeout(n),i(new LI(Hg.WS_ABORT));});});}async request(e){if("closed"===this.ws.state)throw new LI(Hg.WS_DISCONNECT);const t=()=>new cg((e,t)=>{this.ws.once(SI.CLOSED,()=>t(new LI(Hg.WS_ABORT))),this.ws.once(SI.CONNECTED,e);});"connected"!==this.ws.state&&(await t());const i=this.sendMessage(e),n=new cg((e,t)=>{const n=()=>{t(new LI(Hg.WS_ABORT));};this.ws.once(SI.RECONNECTING,n),this.ws.once(SI.CLOSED,n),this.once("req_".concat(i),e),iS(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(SI.RECONNECTING,n),this.ws.off(SI.CLOSED,n),t(new LI(Hg.TIMEOUT,"cross channel ws request timeout"));});}),r=await n;if(!r||200!==r.code)throw new LI(Hg.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r;}async connect(e){this.ws.removeAllListeners(SI.REQUEST_NEW_URLS),this.ws.on(SI.REQUEST_NEW_URLS,t=>{t(e);}),await this.ws.init(e);}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close();}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t;}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval(()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date(),requestId:0});},3e3);}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0;}}class AV extends dT{set state(e){e!==this._state&&(e!==qI.RELAY_STATE_FAILURE&&(this.errorCode=zI.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e);}get state(){return this._state;}constructor(e,t,i,n,r){super(),sh(this,"joinInfo",void 0),sh(this,"sid",void 0),sh(this,"clientId",void 0),sh(this,"cancelToken",sC.CancelToken.source()),sh(this,"workerToken",void 0),sh(this,"requestId",0),sh(this,"signal",void 0),sh(this,"prevChannelMediaConfig",void 0),sh(this,"httpRetryConfig",void 0),sh(this,"_resolution",void 0),sh(this,"_state",qI.RELAY_STATE_IDLE),sh(this,"errorCode",zI.RELAY_OK),sh(this,"onStatus",e=>{jC.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",YI.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.SRC_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=zI.DEST_TOKEN_EXPIRED,this.state=qI.RELAY_STATE_FAILURE));}),sh(this,"onReconnect",async()=>{jC.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",YI.NETWORK_DISCONNECTED),this.state=qI.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==qI.RELAY_STATE_IDLE&&(jC.error("auto restart channel media relay failed",e.toString()),this.errorCode=zI.SERVER_CONNECTION_LOST,this.state=qI.RELAY_STATE_FAILURE);});}),this.joinInfo=e,this.clientId=t,this.sid=rS(),this.signal=new yV(this.joinInfo,this.clientId,i),this.httpRetryConfig=n,this._resolution=r;}async startChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_IDLE)throw new LI(Hg.INVALID_OPERATION);this.state=qI.RELAY_STATE_CONNECTING,await this.connect(),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e);}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new LI(Hg.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e;}this.prevChannelMediaConfig=e;}async updateChannelMediaRelay(e){if(this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e;}async setVideoProfile(e){if(this._resolution=e,this.state!==qI.RELAY_STATE_RUNNING)throw new LI(Hg.INVALID_OPERATION);const t=this.genMessage(KI.SetVideoProfile);await this.signal.request(t),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"));}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),jC.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=qI.RELAY_STATE_IDLE,this.dispose();}dispose(){jC.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=sC.CancelToken.source(),this.state=qI.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0;}async connect(){const e=await fA(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",YI.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect);}async sendStartRelayMessage(e){const t=this.genMessage(KI.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(KI.SetSdkProfile,e);await this.signal.request(i),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(KI.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",YI.PACKET_JOINED_SRC_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(KI.SetSourceUserId,e);await this.signal.request(r),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(KI.SetDestChannel,e);await this.signal.request(s),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",YI.PACKET_JOINED_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(KI.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",YI.PACKET_SENT_TO_DEST_CHANNEL),this.state=qI.RELAY_STATE_RUNNING,jC.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution);}async sendUpdateMessage(e){const t=this.genMessage(KI.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",YI.PACKET_UPDATE_DEST_CHANNEL),jC.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"));}async sendStopRelayMessage(){const e=this.genMessage(KI.StopPacketTransfer);await this.signal.request(e),jC.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"));}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:EC,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.20.2"===s.sdkVersion&&(s.sdkVersion="0.0.1");let o=null,a=null;switch(e){case KI.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case KI.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},s;case KI.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new LI(Hg.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:a.uid+""},s;case KI.SetDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},s;case KI.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case KI.Reconnect:return s.clientRequest={command:"Reconnect"},s;case KI.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case KI.UpdateDestChannel:if(o=t&&t.getDestChannelMediaInfo(),!o)throw new LI(Hg.UNEXPECTED_ERROR,"can not find dest config");return o.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId);}),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},s;case KI.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height};}return s;}}function bV(e){var t={},i=!1;function n(t,n){return i=!0,{done:!1,value:new CU(n=new wU(function(i){i(e[t](n));}),1)};}return t[void 0!==xu&&th||"@@iterator"]=function(){return this;},t.next=function(e){return i?(i=!1,e):n("next",e);},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return n("throw",e);}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):n("return",e);}),t;}var wV=i(OU);function OV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function NV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"statsFilter",void 0),sh(this,"useRTX",!1),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(LV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=gx(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,PV(PV({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{constructor(e){sh(this,"sessionDesc",void 0),sh(this,"localCapabilities",void 0),sh(this,"rtpCapabilities",void 0),sh(this,"candidates",void 0),sh(this,"iceParameters",void 0),sh(this,"dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,sdkCodec:a,cname:c}=e,d=JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=s,this.localCapabilities=o,this.cname=c;for(let e=0;ee.payloadType.toString(10));let e=r.videoCodecs.filter(e=>{var t,i;return null===(t=e.rtpMap)||void 0===t?void 0:bn(i=t.encodingName.toLowerCase()).call(i,a);});0===e.length&&(e=r.videoCodecs),o.attributes.payloads=e,o.attributes.extmaps=r.videoExtensions;}"audio"===o.media.mediaType&&(o.media.fmts=r.audioCodecs.map(e=>e.payloadType.toString(10)),o.attributes.payloads=r.audioCodecs,o.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(o);}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1;}toString(){return JU.print(this.sessionDesc);}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=Cx(t,this.cname),s=this.sessionDesc.mediaDescriptions.find(t=>e===av.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),o=n[0].attributes.label,a=n[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(n),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(r),{id:o,mslabel:a};}batchSend(e){return e.map(e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0);});}stopSending(e){this.sessionDesc.mediaDescriptions.forEach(t=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach(t=>{bn(e).call(e,t.attributes.label||"")?r.push(t):i.push(t);}),t.attributes.ssrcGroups.forEach(e=>{var t;bn(t=r.map(e=>e.ssrcId)).call(t,e.ssrcIds[0])||n.push(e);}),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n;});}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}receive(e,t,i){e.forEach((e,t)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex(e=>e.attributes.mid===i.kind),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r;});}stopReceiving(e){}updateCandidates(e){e===cv.TCP?this.candidates.forEach(e=>{-1===this.candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this.candidates.push(NV(NV({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}));}):this.candidates=this.candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;it.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find(t=>e===av.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid);if(n){const e=n.attributes.ssrcs.find(e=>e.attributes.label===t);var r;e&&(e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i));}}mungMediaDesc(e){const t=YT(e);return vx(t),function(e){const t=e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach(e=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1);});}(t),t;}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return [i];}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:s});const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}send(e,t){var i=this;return PU(function*(){const n=yield IU(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map(e=>i.peerConnection.addTrack(e._mediaStreamTrack)),s=yield IU(i.peerConnection.createOffer()),o=JU.parse(s.sdp),a=e.map(e=>{const t=e._mediaStreamTrack,n=o.mediaDescriptions.find(e=>e.attributes.mid===t.kind);if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter(e=>e.attributes.label===t),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find(e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}];}return [{ssrcId:n[0].ssrcId}];}(n,t.id,i.useRTX);});let c;try{c=yield a;}catch(e){throw r.forEach(e=>{bg()&&e.replaceTrack(null),i.peerConnection.removeTrack(e);}),e;}const d=i.mungSendOfferSDP(s.sdp,e);i.remoteSDP.receive(e,t,c);const l=i.remoteSDP.toString();return yield IU(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IU(i.applySendEncodings(r,e)),yield IU(i.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map((e,t)=>{const i=e._mediaStreamTrack.id;return {localSSRC:a[t],id:i};});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{n();}})();}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{bg()&&e.replaceTrack(null),this.peerConnection.removeTrack(e);});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),s=new cg((t,n)=>{const s=setTimeout(()=>{n(new Error("Cannot receive track, id: ".concat(i)));},1e4),o=n=>{const a=Sg();if(("Safari"===a.name&&11===Number(a.version)||Og())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(r);}if(n.track.id===i)return this.peerConnection.removeEventListener("track",o),clearTimeout(s),void t(n.track);};this.peerConnection.addEventListener("track",o);}),o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return {track:await s,id:i};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map(e=>{if(bg()&&e.track)e.track.enabled=!1;else {const t=e.getParameters();t.encodings.forEach(e=>e.active=!1),e.setParameters(t);}});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"");});if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map(async e=>{if(bg()&&e.track)e.track.enabled=!0;else {const t=e.getParameters();t.encodings.forEach(e=>e.active=!0),await e.setParameters(t);}});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString();yield IU(t.peerConnection.setLocalDescription(n)),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e);}finally{i();}})();}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter(t=>{var i;return (null===(i=t.track)||void 0===i?void 0:i.id)===e;});1===i.length&&(await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getSenders().find(e=>{var i;return (null===(i=e.track)||void 0===i?void 0:i.id)===t;});i&&(await i.replaceTrack(e._mediaStreamTrack));}createDataChannels(e,t){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support createDataChannels.");}stopDataChannels(e){throw new Kg(Hg.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.");}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[],sdpSemantics:"plan-b"};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...LV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>{var i;return (null===(i=t.track)||void 0===i?void 0:i.id)===e._mediaStreamTrack.id;});}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!IA().supportSetRtpSenderParameters)return jC.warn("Browser not support set rtp-sender parameters");const n={},r={};if(e instanceof Rw)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(RC("DSCP_TYPE")&&jg()){var s;const e=RC("DSCP_TYPE");bn(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e);}const o=t.getParameters(),a=null===(i=o.encodings)||void 0===i?void 0:i[0];a&&Object.assign(a,r),Object.assign(o,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(o.encodings))),await t.setParameters(o);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find(e=>e.attributes.mid===n.kind);r&&Ix(r,e);}),JU.print(i);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0;}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map((t,i)=>{let{id:n,mslabel:r}=t;const{kind:s}=e[i];return new cg((e,t)=>{const i=setTimeout(()=>{t(new Error("Cannot receive track, id: ".concat(n)));},1e4),o=t=>{const a=Sg();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(s,n,t.track.id),this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:r,id:n});}if(t.track.id===n)return this.peerConnection.removeEventListener("track",o),clearTimeout(i),void e({track:t.track,id:n});};this.peerConnection.addEventListener("track",o);});}),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await cg.all(t);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=LV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function kV(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;oe.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"remoteCodecs",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"recoveredDataChannelIds",[]),sh(this,"currentDataChannelId",1),sh(this,"mutex",new pS("P2PConnection-mutex")),this.store=t,this.peerConnection=new RTCPeerConnection(jV.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i});}else jC.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.");}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=Px(i),this.initialOffer=e,BV(BV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new Kg(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{get localCapabilities(){return YT(this._localCapabilities);}get rtpCapabilities(){return YT(this._rtpCapabilities);}get candidates(){return YT(this._candidates);}get iceParameters(){return YT(this._iceParameters);}get dtlsParameters(){return YT(this._dtlsParameters);}constructor(e){sh(this,"sessionDesc",void 0),sh(this,"_localCapabilities",void 0),sh(this,"_rtpCapabilities",void 0),sh(this,"_candidates",void 0),sh(this,"_iceParameters",void 0),sh(this,"_dtlsParameters",void 0),sh(this,"setup",void 0),sh(this,"currentMidIndex",void 0),sh(this,"cname",void 0),sh(this,"firefoxSsrcMidMap",new Map()),e=YT(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:s,localCapabilities:o,cname:a}=e,c=JU.parse("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n");this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=o,this.setup=s,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,e.attributes.setup=s,"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:VV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}preloadRemoteMedia(){const e=RC("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;se.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s+1)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||1===t&&(bg()||Lg())||0===t&&RC("USE_SUB_RTX")||kg()?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0};}}sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t};}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n);}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t);}),{mids:i,needExchangeSDP:n};}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||wg()||kg()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0");}),this.updateBundleMids();}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r]);}),this.updateBundleMids();}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}updateCandidates(e){const t=this._candidates.filter(e=>"udp"===e.transport);if(e===cv.TCP){if(0===t.length)return;if(RC("TCP_CANDIDATE_ONLY")){const e=this._candidates.filter(e=>"tcp"===e.transport);t.forEach(t=>{-1===e.findIndex(e=>e.connectionAddress===t.connectionAddress)&&e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}));}),this._candidates=e;}else {const e=[];t.forEach(t=>{e.push(UV(UV({},t),{},{foundation:"tcpcandidate",priority:Number(t.priority)-1+"",transport:"tcp",port:Number(t.port)+90+""}));}),this._candidates=[...t,...e];}}else if(e===cv.RELAY){if(0!==t.length)return;{const e=this._candidates.filter(e=>"tcp"===e.transport);e.forEach(e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}));}),this._candidates=[...t,...e];}}else 0===t.length?(this._candidates.filter(e=>"tcp"===e.transport).forEach(e=>{t.push(UV(UV({},e),{},{foundation:"udpcandidate",priority:Number(e.priority)+1+"",transport:"udp",port:Number(e.port)-90+""}));}),this._candidates=t):this._candidates=this._candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid);}return !1;}return n;});}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return {mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:xV,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0};}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter(e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction);else if(a=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from ").concat(e.attributes.payloads," to ").concat(l)),e.attributes.payloads=l,e.media.fmts=t;}),!0;}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:xV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs;}}({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:s}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});const u=this.peerConnection.getTransceivers()[0];if(null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver),RC("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t);}}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()));}}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t),e._updateRtpTransceiver(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)jC.debug("[P2PConnection] Channels are already available and can be reused directly.");else {const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i);}t.forEach(e=>{e._updateOriginDataChannel(i);});const{needExchangeSDP:n}=this.remoteSDP.sendDataChannel();if(n){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),jC.debug("[P2PConnection] createDataChannels by exchanging SDP.");}else jC.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return;}catch(e){throw e instanceof Kg?e:new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()));}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e);}catch(e){throw e instanceof Kg?e:new Kg(Hg.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()));}}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r,transceiver:o};}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),jC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."));}else jC.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive no need to exchange SDP."));return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:t.receiver.track,id:e,transceiver:t};});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()));}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()));}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e);}finally{i();}})();}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1;}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new Kg(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport,{local:i,remote:n}=t.getSelectedCandidatePair();return {local:BV(BV({},$U),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:BV(BV({},$U),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port})};}return this.statsFilter.getSelectedCandidatePair();}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...jV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),RC("ENABLE_ENCODED_TRANSFORM")&&IA().supportWebRTCEncodedTransform&&(t.encodedInsertableStreams=!0),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state));},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e);};const i=t.iceTransport;i&&(i.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var i;e&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,e));},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:e,remote:t}=i.getSelectedCandidatePair();jC.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:e.type,protocol:e.protocol}),", remote ").concat(JSON.stringify({candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port})," )"));}}));}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null));}async updateRtpSenderEncodings(e,t){var i;if(!t){t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack);}if(!t)return jC.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return jC.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!IA().supportSetRtpSenderParameters)return jC.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const n={},r={};switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced";}if(e._encoderConfig){var s;const{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(r.maxBitrate=1e3*t),(bn(s=e._hints).call(s,jA.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(r.maxFramerate=Sy(i)),n&&n>=1&&(r.scaleResolutionDownBy=n));}if(RC("DSCP_TYPE")&&jg()){var o;const e=RC("DSCP_TYPE");bn(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e);}const a=t.getParameters(),c=null===(i=a.encodings)||void 0===i?void 0:i[0];wg()&&!c&&(n.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,n),jC.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a);}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let i=0;i{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&(i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n)),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=jV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function GV(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;oe.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,Lx(e),RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1;}updateRemoteRTPCapabilities(e){const t=JU.parse(KV);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const e of t.mediaDescriptions){if(e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=i.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:zV,rtx:RC("USE_SUB_RTX")?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}if("audio"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,RC("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=Cx([{ssrcId:qV}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i;}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1;}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let s=1;se.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:r.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*s)}}),this.currentMidIndex+=2;}this.updateBundleMids();}toString(){return JU.print(this.sessionDesc);}send(e,t,i,n){const{ssrcs:r,ssrcGroups:s}=Cx(t,this.cname,RC("SYNC_GROUP")?i:void 0),o=this.findPreloadMediaDesc(r);if(o){if(wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,o.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(o);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(o,n),{mid:o.attributes.mid,needExchangeSDP:!0};}return {mid:o.attributes.mid,needExchangeSDP:!1};}{const t=this.findAvailableMediaIndex(e,r);let i;return -1===t||bg()||Og()||Lg()||0===t&&RC("USE_SUB_RTX")?(i=this.createOrRecycleSendMedia(e,r,s,"sendonly",n),this.updateBundleMids()):(i=YT(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),wg()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0};}}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n);}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t);}),{mids:i,needExchangeSDP:n};}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||wg()||bg()||Og()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0");}),this.updateBundleMids();}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive";}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly";}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive";});}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>bn(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly";});}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r]);}),this.updateBundleMids();}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive";}),this.updateBundleMids();}updateCandidates(e){e===cv.TCP?this._candidates.forEach(e=>{-1===this._candidates.findIndex(t=>"tcp"===t.transport&&t.connectionAddress===e.connectionAddress&&t.port===e.port)&&this._candidates.push(HV(HV({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}));}):this._candidates=this._candidates.filter(e=>"tcp"!==e.transport);for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates;}restartICE(e){e=YT(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd;});}predictReceivingMids(e){const t=[];for(let i=0;i{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(wg()){if(n){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return !(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid);}return !1;}return n;});}createOrRecycleRecvMedia(e,t,i,n,r,s){const o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Mx(o,a,this.localCapabilities.send,o===av.VIDEO?n:r),d=o===av.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:o,port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,s);const h=this.findFirstClosedMedia(o);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u;}else this.sessionDesc.mediaDescriptions.push(u);return u;}updateRemoteCodec(e,t,i){const n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))],r=new Set(t);if(n.every(e=>r.has(e)))return jC.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const s=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return bn(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t);}));if(0===s.length)return jC.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;const o=[...new Set(s.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];let a;if(jC.debug("updateRemoteCodec, from ".concat(n," to ").concat(o)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter(e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction);else if(a=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&bn(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction),a.length!==e.length)return jC.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;this._rtpCapabilities.recv.videoCodecs=s;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Mx(av.VIDEO,d,c,i);return a.forEach(e=>{const t=l.map(e=>e.payloadType.toString(10));jC.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from ").concat(e.attributes.payloads," to ").concat(l)),e.attributes.payloads=l,e.media.fmts=t;}),!0;}createOrRecycleSendMedia(e,t,i,n,r){const s=this.rtpCapabilities.send,o=e===av.VIDEO?s.videoCodecs:s.audioCodecs,a=e===av.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:YV,protos:["UDP","TLS","RTP","SAVPF"],fmts:o.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:o,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d;}else this.sessionDesc.mediaDescriptions.push(d);return d;}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid);}mungRecvMediaDsec(e,t,i){const n=YT(e);return vx(n),Ix(n,t),yx(n,t),Ax(n),bx(n,i,this.localCapabilities.send),n;}mungSendMediaDesc(e,t){const i=YT(e);return bx(i,t,this.localCapabilities.recv),Lx(i),i;}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e;}}bumpMid(e){this.currentMidIndex+=e;}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>wg()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port);}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return (null===(i=t.attributes)||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId)===e[0].ssrcId;});}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs;}}function XV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function QV(e){for(var t=1;te.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}))];}constructor(e,t,i){super(e,t),sh(this,"store",void 0),sh(this,"peerConnection",void 0),sh(this,"remoteSDP",void 0),sh(this,"initialOffer",void 0),sh(this,"transportEventReceiver",void 0),sh(this,"statsFilter",void 0),sh(this,"useXR",RC("USE_XR")),sh(this,"localCapabilities",void 0),sh(this,"localCandidateCount",0),sh(this,"allCandidatesReceived",!1),sh(this,"remoteCodecs",void 0),sh(this,"dataStreamChannelMap",new Map()),sh(this,"establishPromise",void 0),sh(this,"mutex",new pS("NVExtentionsConnection-mutex")),sh(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=Ex(this.peerConnection,RC("STATS_UPDATE_INTERVAL"),void 0,wg()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish();}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=Tx(e.sdp),i=await Ox({filterRTX:!RC("USE_PUB_RTX")&&!RC("USE_SUB_RTX"),filterVideoFec:RC("FILTER_VIDEO_FEC"),filterAudioFec:RC("FILTER_AUDIO_FEC"),filterVideoCodec:RC("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=i,this.initialOffer=e,QV(QV({},t),{},{rtpCapabilities:i,offerSDP:e.sdp});}catch(e){throw new LI(Hg.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString());}}async connect(e,t,i,n,r,s){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new JV({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:Px(this.localCapabilities),cname:s});const o=this.remoteSDP.toString(),a=JU.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&Lx(c),this.useXR&&kx(a);const d=JU.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()));}}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void jC.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i});}else jC.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.");}async updateRemoteConnect(e){var t,i,n,r;(null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0)&&(null===(r=this.remoteSDP)||void 0===r||r.updateRemoteCodec([],this.remoteCodecs,this.store.codec));null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const s=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),jC.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.");}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From NVExtentionsConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const s=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});s.push(t);}),wg()&&!0===RC("SIMULCAST")&&(yield IU(n.applySimulcastForFirefox(s,e)));const o=yield IU(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(o.sdp,e,a),d=JU.parse(c),l=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return Sx(t,RC("USE_PUB_RTX"));});let u;try{u=yield l;}catch(r){u=[],n.remoteSDP.receive(e,t,i,u);const s=n.remoteSDP.toString();throw yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:s})),yield IU(n.stopSending(a,!0)),r;}n.remoteSDP.receive(e,t,i,u);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield IU(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IU(n.applySimulcastEncodings(s,e)),yield IU(n.applySendEncodings(s,e)),null==p||p(h),yield IU(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),s.map((e,t)=>{const i=a[t];return {localSSRC:l[t],id:i,transceiver:e};});}catch(e){throw e instanceof LI?e:new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(e.toString()));}finally{r();}})();}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.");t.map(e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e);});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const s=this.remoteSDP.toString();null==r||r(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(e.toString()));}finally{i&&i();}}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);return i&&"open"===i.readyState?jC.debug("[P2PConnection] Channels are already available and can be reused directly."):(i=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)),void t.forEach(e=>{e._updateOriginDataChannel(i);});}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,"NVExtentionsConnection.createDataChannels failed; ".concat(e.toString()));}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return null==t||t.close(),void this.dataStreamChannelMap.delete(e);}catch(e){throw e instanceof LI?e:new LI(Hg.DATACHANNEL_FAILED,"NVExtentionsConnection.stopDataChannels failed; ".concat(e.toString()));}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:s}=this.remoteSDP.send(e,t,i,n);if(s){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),s=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(s||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:s}),jC.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."));}else jC.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));const o=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:o.receiver.track,id:r};}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()));}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),jC.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.");}else jC.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return {track:t.receiver.track,id:e};});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()));}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(e.toString()));}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(e.toString()));}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n);}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(e.toString()));}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(e.toString()));}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly";});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()));}}restartICE(e){var t=this;return PU(function*(){const i=yield IU(t.mutex.lock("From NVExtentionsConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(IA().supportPCSetConfiguration){const i=t.peerConnection.getConfiguration(),n=e===cv.RELAY?"relay":"all";i.iceTransportPolicy!==n&&(jC.debug("restartICE change iceTransportPolicy from [".concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i));}else if(e===cv.RELAY)return;e!==cv.RELAY&&t.remoteSDP.updateCandidates(e);const n=yield IU(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const r=Tx(n.sdp),{remoteIceParameters:s}=yield r.iceParameters;t.remoteSDP.restartICE(s);const o=t.remoteSDP.toString(),a=t.logSDPExchange(n.sdp||"","offer","local","restartICE");yield IU(t.peerConnection.setLocalDescription(n)),null==a||a(o),yield IU(t.peerConnection.setRemoteDescription({type:"answer",sdp:o}));}catch(e){jC.warning("restart ICE failed, abort operation",e);}finally{i();}})();}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear();}getStats(){return this.statsFilter.getStats();}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e);}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),s=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==s||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});}catch(e){throw new LI(Hg.EXCHANGE_SDP_FAILED,e.toString());}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?wg()||(await this.applySimulcastEncodings(i,[t])):await this.applySendEncodings(i,[t]));}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t);}async replaceTrack(e,t){const i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&(await i.sender.replaceTrack(e._mediaStreamTrack));}getP2PConnectionParams(){var e;if(null===(e=this.peerConnection.currentLocalDescription)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error();return QV(QV({},Tx(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities});}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState);},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState);},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,jC.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount));},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,jC.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount));},RC("CANDIDATE_TIMEOUT"));}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...ZV.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}async applySendEncodings(e,t){try{if(!IA().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let l=0;l1&&(t.scaleResolutionDownBy=h._encoderConfig.scaleResolutionDownBy);if(RC("DSCP_TYPE")&&jg()){var d;const e=RC("DSCP_TYPE");bn(d=["very-low","low","medium","high"]).call(d,e)&&(t.networkPriority=e);}const l=u.sender.getParameters(),p=null===(r=l.encodings)||void 0===r?void 0:r[0];wg()&&!p&&(e.encodings=[t]),p&&Object.assign(p,t),Object.assign(l,e),await u.sender.setParameters(l);}}}catch(e){jC.debug("Apply RTPSendEncodings failed.");}}mungSendOfferSDP(e,t,i){const n=JU.parse(e);return t.forEach((e,t)=>{const r=i[t],s=n.mediaDescriptions.find(e=>e.attributes.mid===r);s&&(Ix(s,e),wx(s,e,this.store.codec));}),JU.print(n);}mungReceiveAnswerSDP(e,t,i){const n=JU.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===av.AUDIO&&"audio"===r.media.mediaType&&Lx(r),this.useXR&&kx(n),JU.print(n);}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e);},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e);},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i);},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t);},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e);};}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0;}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a200&&null!==(s=d._scalabilityMode)&&void 0!==s&&s.numSpatialLayers&&(null===(o=d._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e));}}}async applySimulcastEncodings(e,t){if(!wg()&&e.length===t.length)for(let i=0;i200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(s=e._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("exchanging ".concat(i," ").concat(t," SDP during NVExtentionsConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId;}setConfiguration(e){if(IA().supportPCSetConfiguration){const t=ZV.resolvePCConfiguration(e);this.peerConnection.setConfiguration(t);}}}function $V(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From NVExtentionsConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{const n=setTimeout(()=>{this.closeSignal(),t(new LI(Hg.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(i))));},2e3);this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void e();},this.dataChannel.onerror=e=>{this.closeSignal(),t(e);};}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)};}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t);}send(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From DataChannelConnection.send"));try{return yield*bV(eF(n._p2pConnection.send(e,t,i)));}finally{r();}})();}async stopSending(e,t){return this._p2pConnection.stopSending(e,t);}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t);}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e);}async receive(e,t,i,n){return this._nvMedia?(jC.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(jC.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n));}async batchReceive(e){return [...(await this._p2pConnection.batchReceive(e))];}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e);}async muteRemote(e){return await this._p2pConnection.muteRemote(e);}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e);}async muteLocal(e){return await this._p2pConnection.muteLocal(e);}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e);}restartICE(e){var t=this;return PU(function*(){return yield*bV(eF(t._p2pConnection.restartICE(e)));})();}close(){var e;null===(e=this._nvMedia)||void 0===e||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection);}getStats(){return this._p2pConnection.getStats();}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e);}updateRemoteConnect(e){var t;null===(t=this._nvMedia)||void 0===t||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e);}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t);}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t);}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t);}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t);}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e);}logSDPExchange(e,t,i,n){if(RC("SDP_LOGGING"))return jC.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n);}:void 0;}static resolvePCConfiguration(e){const t={iceServers:[]};return e.iceServers?t.iceServers=e.iceServers:e.turnServer&&"off"!==e.turnServer.mode&&(RT(e.turnServer.servers)?t.iceServers=e.turnServer.servers:(t.iceServers&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.servers)),RC("USE_TURN_SERVER_OF_GATEWAY")&&t.iceServers&&e.turnServer.serversFromGateway&&t.iceServers.push(...iF.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),RC("FORCE_TURN_TCP")?t.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(t.iceTransportPolicy="relay");}))),t;}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(gy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!RC("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}));}),t;}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i);},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e);},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t);},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?void 0:i.call(this,e,t);};}closeSignal(){this.dataChannel.close(),this.peerConnection.close();}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0;}setConfiguration(e){this._p2pConnection.setConfiguration(e);}}function nF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){s[1].track._originMediaStreamTrack.stop();}await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createMuteMessage(r);await yT(this,hv.RequestMuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==uv.Connected)return void i(new Kg(Hg.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const s=r.find(e=>"videoLowTrack"===e[0]);if(s){const t=s[1];if(t.track._originMediaStreamTrack.stop(),!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}else {const i=Gx(e,bT(this,hv.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i;}await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t;}));const o=this.createUnmuteMessage(r);await yT(this,hv.RequestUnmuteLocal,o),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return void t();const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),await this.connection.updateEncoderConfig(r,s),this.emit(hv.UpdateVideoEncoder,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(lv.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==uv.Connected)return;const{id:r,track:s}=i;await this.connection.updateSendParameters(r,s),t();}catch(e){i(e);}finally{n();}}),sh(this,"handleReplaceMixingTrack",async(e,t,i,n)=>{if(!this.connection||this.state!==uv.Connected)return void t();const r=dV([e]);let s;jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof n&&n||(s=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t();}catch(e){i(e);}finally{var o;null===(o=s)||void 0===o||o();}}),sh(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;jC.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var s;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!this.connection||!i||this.state!==uv.Connected)return void t();if(await(null===(s=this.connection)||void 0===s?void 0:s.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t);}if(i[0]===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}t();}catch(e){i(e);}finally{var o;null===(o=r)||void 0===o||o();}}),sh(this,"handleGetRTCStats",e=>{e(this.statsCollector.getRTCStats());}),sh(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats());}),sh(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats());}),sh(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),sh(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new rV(this.store),this.bindStatsUploaderEvents(),this.isPlanB=!IA().supportUnifiedPlan||RC("CHROME_FORCE_PLAN_B")&&jg(),this.shouldForwardP2PCreation=RC("FORWARD_P2P_CREATION")&&IA().supportPCSetConfiguration&&function(){const e=Rg();return e===_g.ANDROID||e===_g.IOS||e===_g.HARMONY_OS;}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection));}async startP2PConnection(e,t){var i;this.state=uv.New;const n=this.shouldForwardP2PCreation&&"closed"===(null===(i=this.connection)||void 0===i?void 0:i.peerConnectionState);if(this.shouldForwardP2PCreation&&!n||(n&&this.connection&&(jC.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new iF(e,this.store):this.isPlanB?new LV(e,this.store):new jV(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=RC("NEW_ICE_RESTART")?dv.FIRST_CONNECTION:dv.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(e),this.connection.establishPromise;}async connect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof iF?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected);}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter(e=>{var t;let[i]=e;return bn(t=[lv.LocalVideoLowTrack,lv.LocalVideoTrack]).call(t,i);}),i=t.map(e=>{let[,{id:t}]=e;return t;}),n=t.map(e=>{let[t]=e;return t;});if(this.connection instanceof jV){if(eI.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!bn(e).call(e,this.store.codec)){const t=["vp8","h264"].find(t=>bn(e).call(e,t));t&&(this.store.codec=t,jC.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")));}this.connection.updateRemoteRTPCapabilities(i,e);}}async preConnect(e,t,i,n,r,s){if(!this.connection)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const o=await this.connection.connect(e,t,i,n,r,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=uv.Connected,o;}getEstablishParams(){if(this.connection instanceof iF)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams");}async publishDataChannel(e){if(!this.connection||this.state!==uv.Connected){if(this.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return void e.forEach(e=>{var t;bn(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e);});}const t=this.filterTobePublishedDataChannels(e);0!==t.length&&(t.forEach(e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t);}),await this.connection.createDataChannels(this.store.uid,t),t.forEach(e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t);}));}publish(e,t,i){var n=this;return PU(function*(){const r=yield IU(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==uv.Connected){if(n.state===uv.Disconnected)throw new Kg(Hg.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter(e=>-1===n.pendingLocalTracks.indexOf(e));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t));}n.store.pubId=n.store.pubId+1,RU.markPublishStart(n.store.clientId,n.store.pubId);const s=n.filterTobePublishedTracks(e,t,i);if(0===s.length)return void(yield IU(n.tryToUnmuteAudio(e)));yield*bV(oF(n.doPublish(n.connection,s)));}finally{r();}})();}doPublish(e,t){var i=this;return PU(function*(){t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?"audio":"video",r);}),i.bindLocalTrackEvents(t);const n=t.map(e=>{let{track:t}=e;return t;}),r=yield IU(e.send(t.map(e=>{let{track:t}=e;return t;}),i.store.codec,i.store.audioCodec)),s=(yield IU(r.next())).value,o=i.createGatewayPublishMessage(t,s);let a;try{a=yield o;}catch(e){throw r.throw(e),(null==e?void 0:e.code)===Hg.WS_ABORT&&t.forEach(e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t);}),i.unbindLocalTrackEvents(t),e;}const c=i.mapPubResToRemoteConfig(o,a),d=(yield IU(r.next(c))).value,l=RC("ENABLE_VIDEO_SEI");n.forEach(async e=>{const t=e.getRTCRtpTransceiver();t&&l&&(e.trackMediaType===av.VIDEO?await async function(e,t){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support video encoded transform");if(mU.has(e))return;if(!e.track)return;const i={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams();}catch(e){return void jC.error("create video-encoded-streams error",e&&e.message);}let s=[];t.on("sei-to-send",e=>{s.push(e);});const o=new TransformStream({transform(t,r){i.controller||(i.controller=r),e.track&&e.track.id!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));const o=s.shift();o&&(t.data=EU(t.data,o)),r.enqueue(t);}});r.readable.pipeThrough(o).pipeTo(r.writable);}else {if(!bg())return;{if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const r=lU(),s=new MessageChannel();await new cg(e=>r.onmessage=t=>{"registered"===t.data&&e(void 0);});const o=new RTCRtpScriptTransform(r,{name:"tx",port:s.port2},[s.port2]);e.transform=o,await new cg(e=>r.onmessage=t=>{"started"===t.data&&e(void 0);}),t.on("sei-to-send",e=>{s.port1.postMessage({sei:e});}),s.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==i.track.id&&(jC.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",n),i.track=e.track,i.track.addEventListener("ended",n));},i.worker=r;}}function n(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",n);}const t=mU.get(e);if(t){mU.delete(e);try{var i,r;null===(i=t.controller)||void 0===i||i.terminate(),null===(r=t.worker)||void 0===r||r.terminate();}catch(e){jC.warning(e&&e.message);}}}mU.set(e,i),e.track.addEventListener("ended",n);}(t.sender,e):e.trackMediaType===av.AUDIO&&(await async function(e){if(!IA().supportWebRTCEncodedTransform)return void jC.warning("browser not support audio encoded transform");if(uU.has(e))return;if(!e.track)return;const t={track:e.track};if(Ag()){if(!e.createEncodedStreams)return void jC.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams();}catch(e){return void jC.error("create audio-encoded-streams error",e&&e.message);}const r=new TransformStream({transform(n,r){t.controller||(t.controller=r),e.track&&e.track.id!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i)),r.enqueue(n);}});n.readable.pipeThrough(r).pipeTo(n.writable);}else if(bg()){if("undefined"==typeof RTCRtpScriptTransform)return void jC.warning("browser not support RTCRtpScriptTransform");const n=lU(),r=new MessageChannel();await new cg(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0);});const s=new RTCRtpScriptTransform(n,{name:"tx",port:r.port2},[r.port2]);e.transform=s,await new cg(e=>n.onmessage=t=>{"started"===t.data&&e(void 0);}),r.port1.onmessage=n=>{var r;n.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==t.track.id&&(jC.debug("audio track changed: ".concat(t.track.id," => ").concat(e.track.id)),t.track.removeEventListener("ended",i),t.track=e.track,t.track.addEventListener("ended",i));},t.worker=n;}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i);}const t=uU.get(e);if(t){uU.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate();}catch(e){jC.warning(e&&e.message);}}}uU.set(e,t),e.track.addEventListener("ended",i);}(t.sender)));}),t.forEach(e=>{let{type:t}=e;i.statsCollector.addLocalStats(t);}),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===lv.LocalAudioTrack?"audio":"video",void 0,r);});})();}async updateVideoStreamParameter(e,t){const i=this.localTrackMap.get(t);if(!i)return;if(!(i.track instanceof Rw))return jC.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof jV||this.connection instanceof LV))return jC.warn("[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB");const{track:n}=i,r=function(e,t){const i={};return e.height&&e.width&&(i.scaleResolutionDownBy=yy(e,t)),i.maxFramerate=e.framerate?Sy(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i;}(e,n);if(n._encoderConfig||(n._encoderConfig={}),t!==lv.LocalVideoLowTrack||!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else {const t=n._originMediaStreamTrack;if(!t.canvas)return jC.warn("[".concat(n.getTrackId(),"] no canvas on track"));!function(e,t){const i=e.canvas;t.width&&(i.width=Sy(t.width)),t.height&&(i.height=Sy(t.height)),t.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=Tb(()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture();},Sy(t.framerate)));}(t,e);}null!=r.maxBitrate&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(n._encoderConfig.frameRate&&"object"==typeof n._encoderConfig.frameRate?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),jC.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),await this.connection.updateRtpSenderEncodings(n);}publishLowStream(e){var t=this;return PU(function*(){if(!t.connection||t.state!==uv.Connected)return;const i=yield IU(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(lv.LocalVideoTrack);if(!r)throw new Kg(Hg.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(lv.LocalVideoLowTrack))throw new Kg(Hg.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const s=[{track:t.getLowVideoTrack(r.track,e),type:lv.LocalVideoLowTrack}];if(yield*bV(oF(t.doPublish(t.connection,s))),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(lv.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield IU(t.connection.muteLocal([e])));}}finally{i();}})();}async republish(){this.pendingLocalTracks.length>0&&(jC.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await vT(this,hv.RequestRePublish,this.pendingLocalTracks),this.emit(hv.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(jC.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await vT(this,hv.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]);}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==av.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==av.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1);}if(e)await vT(this,hv.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===av.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(hv.MediaReconnectEnd,t.uid);}),this.pendingRemoteTracks=[];}async unpublish(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach(e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1);});const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find(e=>"videoLowTrack"===e[0]);if(i){i[1].track.close();}return this.doUnpublish(this.connection,t);}async unpublishDataChannel(e){if(!this.connection||this.state!==uv.Connected)return void e.forEach(e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1);});const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach(e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1);}),0===this.localDataChannels.length&&(await this.connection.stopDataChannels(this.store.uid)),t.map(e=>e.id)):void 0;}async unpublishLowStream(){if(!this.connection||this.state!==uv.Connected)return;const e=this.localTrackMap.get(lv.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[lv.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t);}async doUnpublish(e,t){const i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map(e=>{let[,{id:t}]=e;return t;})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return {type:t,track:i};})),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t);}),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i;}async subscribeDataChannel(e,t){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=t.filter(t=>{var i;return !(null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.get(t.id));});if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEach(t=>{var i;this.remoteDataChannelMap.has(e)?null===(i=this.remoteDataChannelMap.get(e))||void 0===i||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const n=this.pendingRemoteDataChannels.findIndex(i=>{let{user:n,id:r}=i;return n.uid===e.uid&&r===t.id;});-1!==n&&this.pendingRemoteDataChannels.splice(n,1);}),i.map(e=>e.id);}async subscribe(e,t,i,n,r){var s;if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(s=this.remoteUserMap.get(e))&&void 0!==s&&s.has(t))return;let o,a,c;if(r){const i=r.find(e=>{let{stream_type:i}=e;return i===t;});if(!i)throw new Kg(Hg.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);this.connection instanceof jV&&(c=n.transceiver),o=n.track,a=n.id;}else {const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);this.connection instanceof jV&&(c=r.transceiver),o=r.track,a=r.id;}t===av.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Nw(o,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new Ow(o,e.uid,e._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),RC("ENABLE_VIDEO_SEI")&&c&&(t==av.VIDEO?await gU(c.receiver,{onSei:t=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t);}}):t==av.AUDIO&&(await pU(c.receiver)));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const l=this.pendingRemoteTracks.findIndex(i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r;});-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(hv.MediaReconnectEnd,e.uid));}async massSubscribe(e){return this.massSubscribeNoLock(e);}async massSubscribeNoLock(e){if(!this.connection||this.state!==uv.Connected)throw new Kg(Hg.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter(e=>{var t;let{user:i,mediaType:n}=e;return !(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n));});const t=await this.connection.batchReceive(e.map(e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return {kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)};}));e.forEach((e,i)=>{let{user:n,mediaType:r}=e;const{track:s,id:o,transceiver:a}=t[i];r===av.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(s):(n._audioTrack=new Nw(s,n.uid,n._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(n._audioTrack.getTrackId()))),a&&n._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(s):(n._videoTrack=new Ow(s,n.uid,n._uintid,this.store),jC.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(n._videoTrack.getTrackId()))),a&&n._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(n,n._videoTrack));const c=this.remoteUserMap.get(n);c?c.set(r,o):this.remoteUserMap.set(n,new Map([[r,o]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadInboundStats();const d=this.pendingRemoteTracks.findIndex(e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i;});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(hv.MediaReconnectEnd,n.uid));});}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter(i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid;});if(n.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),this.connection&&this.state===uv.Connected||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===av.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0;}}),!this.connection||this.state!==uv.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map(e=>{let[,{id:t}]=e;return t;}));const s=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach(e=>{let[t,{kind:n}]=e;var r,s;n===av.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(s=t._videoTrack)||void 0===s||s._destroy(),t._videoTrack=void 0);else if(n===av.AUDIO){var o;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0;}}),s;}async unsubscribeDataChannel(e,t){if(t.forEach(e=>{const t=this.pendingRemoteDataChannels.findIndex(t=>t.id===e.id);-1!==t&&this.pendingRemoteDataChannels.splice(t,1);}),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach(e=>{e._close();});const n=this.remoteDataChannelMap.get(e);return i.forEach(e=>{n&&n.delete(e.id);}),n&&0===n.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map(e=>e.id);}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e);}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter(e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid;});e.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1);}),t=t.concat(e);}if(!this.connection||this.state!==uv.Connected)return void t.forEach(e=>{let{user:t,kind:i}=e;var n;if(i===av.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===av.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;}});const i=BT(e).call(e,(e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r);},[]);if(0===i.length)return;await this.connection.stopReceiving(i.map(e=>{let[,{id:t}]=e;return t;}));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach(e=>{let[t,{kind:i}]=e;var n,r;i===av.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===av.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===av.AUDIO){var s;this.unbindRemoteTrackEvents(t._audioTrack),null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0;}}),n;}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const n=t===av.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1);}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t);}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void jC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||jC.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));}getAllTracks(e){const t=this.localTrackMap.get(lv.LocalAudioTrack);if((null==t?void 0:t.track)instanceof nw){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==lv.LocalAudioTrack;}).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;}).concat(i.trackList);}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return !(e&&i===lv.LocalVideoLowTrack);}).map(e=>{let[,{track:t}]=e;return t;});}getAllDataChannels(){return this.localDataChannels;}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(lv.LocalAudioTrack),s=n?this.localTrackMap.get(lv.LocalVideoLowTrack):this.localTrackMap.get(lv.LocalVideoTrack);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==s?void 0:s.track.getTrackLabel(),screenshare:-1!==(null==s?void 0:s.track._hints.indexOf(jA.SCREEN_TRACK)),audio:!!i,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}else {var s;i||(i=[]);const o=i.find(e=>e instanceof ew),a=n?null===(s=this.localTrackMap.get(lv.LocalVideoTrack))||void 0===s?void 0:s.track:i.find(e=>e instanceof Rw);eI.publish(this.store.sessionId,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==o?void 0:o.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(jA.SCREEN_TRACK)),audio:!!o,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r});}}reportSubscribeEvent(e,t,i,n){const r=n===av.VIDEO?i._videoSSRC:i._audioSSRC;r&&eI.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===av.VIDEO,audio:n===av.AUDIO,peerid:i.uid,subscribeRequestid:n===av.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,r)});}reset(){jC.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new pS("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(lv.LocalAudioTrack);if((null==e?void 0:e.track)instanceof nw){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e);});}e.track.close();}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=uv.Disconnected;}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats();}getRemoteVideoIsReady(e){var t;return (null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1;}getLocalAudioVolume(){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(e)return e.track.getVolumeLevel();}getLocalVideoSize(){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(e)return {width:e.track._videoWidth||0,height:e.track._videoHeight||0};}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof Rw||t&&t.track instanceof ew?t.track._encoderConfig:void 0;}getLocalMedia(e){return this.localTrackMap.get(e);}hasLocalMedia(){return this.localTrackMap.size>0;}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return !!i&&(!t||i.has(t));}getRemoteMedia(e){var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{};}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return {uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0};});const t=this.localTrackMap.get(lv.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ep(e).call(e,(e,t)=>e.level-t.level),e;}async disconnectForReconnect(){this.connection&&(jC.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=uv.Reconnecting,RC("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t]=e;var i;t._videoTrack&&t._videoTrack._player&&(null===(i=t._videoTrack._player.getVideoElement())||void 0===i||i.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop());}),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:n}]=e;switch(i){case lv.LocalVideoTrack:bn(t=n._hints).call(t,jA.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case lv.LocalAudioTrack:n instanceof nw?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case lv.LocalVideoLowTrack:}}),this.emit(hv.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e);}),this.emit(hv.MediaReconnectStart,t.uid);}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach(e=>{this.pendingLocalDataChannels.push(e);}),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach(e=>{let[t,i]=e;Array.from(ph(i).call(i)).forEach(e=>{this.setPendingRemoteDataChannel(t,e);});}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),jC.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")));}hasPendingRemoteDataChannel(e,t){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&r===t)return !0;}return !1;}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t});}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof sV?e.uid:e)===n.uid&&t===r)return !0;}return !1;}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t});}restartICE(e){var t=this;return PU(function*(){if(!t.connection||t.state!==uv.Connected||t.connection instanceof iF)return;const i=yield IU(t.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield IU(t.connection.restartICE(e));const r=yield IU(n.next());if(r.done)return;const s=r.value,o=yield s;switch(t.reportPCDisconnectedOrFailed(e),e){case cv.TCP:t._pcStatsUploadType=dv.TCP_RESTART;break;case cv.RELAY:t._pcStatsUploadType=dv.RELAY_RESTART;break;default:t._pcStatsUploadType=dv.OLD_RESTART;}t._isInRestartIce=!0,n.next(o);}catch(e){var r;null===(r=n)||void 0===r||r.throw(e);}finally{i();}})();}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalAudioTrack),n=e.videoSend.find(e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId)),r=e.audioSend.find(e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId));if(!n||!r)return 1;const s=AT(this,hv.NeedSignalRTT),o=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=o&&a?(o+a)/2:o||a,d=(c&&s?(c+s)/2:c||s)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(jA.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return nI[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u];}}return u;}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,s=n._videoSSRC,o=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===s);if(!o&&!a)return void(t+=1);const c=AT(this,hv.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=o?o.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5;}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t;}async muteLocalTrack(e){return new cg((t,i)=>{this.handleMuteLocalTrack(e,t,i);});}async replaceTrack(e,t){var i;if(jC.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==uv.Connected)return;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(!n)return;const r=n[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),n[1].track=t),await(null===(i=this.connection)||void 0===i?void 0:i.replaceTrack(t,n[1].id)),this.isPlanB){const e=n[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e);}if(r===lv.LocalVideoTrack&&!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding){const t=this.localTrackMap.get(lv.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new cg((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0);});}}}filterTobePublishedTracks(e,t,i){const n=[],r=this.getAllTracks();e=HT(e=e.filter(e=>-1===r.indexOf(e)));let s,o=!1;const a=this.localTrackMap.get(lv.LocalAudioTrack);for(const r of e){if(r instanceof Rw&&(this.localTrackMap.has(lv.LocalVideoTrack)||o?new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:r,type:lv.LocalVideoTrack}),o=!0),t)){const e=this.getLowVideoTrack(r,i);n.push({track:e,type:lv.LocalVideoLowTrack});}if(r instanceof ew)if(a){const e=a.track;if(e instanceof nw)cV([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else {const t=dV([e,r]);jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t);}}else if(s instanceof nw)cV([r]),s.addAudioTrack(r);else if(s||!r._useAudioElement&&IA().webAudioMediaStreamDest&&!r._bypassWebAudio){s=dV(s?[r,s]:[r]);}else s=r;}return s&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(s.getTrackId(),"]")),n.push({track:s,type:lv.LocalAudioTrack})),n;}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=HT(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof ew){const e=this.localTrackMap.get(lv.LocalAudioTrack);if(!e)continue;e.track instanceof nw?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([lv.LocalAudioTrack,e]),e.track.close())):t.push([lv.LocalAudioTrack,e]);}if(i instanceof Rw){const e=this.localTrackMap.get(lv.LocalVideoTrack);if(!e)continue;t.push([lv.LocalVideoTrack,e]);const i=this.localTrackMap.get(lv.LocalVideoLowTrack);i&&t.push([lv.LocalVideoLowTrack,i]);}}return t;}filterTobePublishedDataChannels(e){return e=(e=HT(e)).filter(e=>-1===this.localDataChannels.findIndex(t=>t.id===e.id));}filterTobeUnpublishedDataChannels(e){return e=(e=(e=HT(e)).filter(e=>-1!==this.localDataChannels.indexOf(e))).filter(e=>e._originDataChannel);}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.addListener(BA.GET_STATS,this.handleGetLocalVideoStats),t.addListener(BA.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}bindLocalAudioTrackEvents(e,t){e instanceof nw?e.trackList.forEach(e=>{e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.addListener(BA.GET_STATS,this.handleGetLocalAudioStats),e.addListener(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)));}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return {track:i,type:t};})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case lv.LocalVideoTrack:t.off(BA.GET_STATS,this.handleGetLocalVideoStats),t.off(BA.GET_RTC_STATS,this.handleGetRTCStats),t.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(BA.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(BA.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case lv.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case lv.LocalVideoLowTrack:}});}unbindLocalAudioTrackEvents(e){e instanceof nw?e.trackList.forEach(e=>{e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);}):(e.off(BA.GET_STATS,this.handleGetLocalAudioStats),e.off(BA.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(BA.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(BA.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(BA.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(BA.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack));}bindRemoteTrackEvents(e,t){t instanceof Ow&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e));}),t instanceof Nw&&t.addListener(BA.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e));});}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(BA.GET_STATS);}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(av.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(av.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack);});}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var n;let r,s,{track:o,type:a}=e;switch(a){case lv.LocalAudioTrack:r=JI.Audio,s={dtx:o instanceof tw&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case lv.LocalVideoTrack:r=bn(n=o._hints).call(n,jA.SCREEN_TRACK)?JI.Screen:JI.High,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});break;case lv.LocalVideoLowTrack:r=JI.Low,s=sF(sF({},Ry(o)),{},{codec:this.store.codec});}return {stream_type:r,attributes:s,ssrcs:t[i]};});}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,id:t[i].id,ssrcs:t[i].localSSRC});});}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t);});}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(hv.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),RC("NEW_ICE_RESTART")){var i;if(bn(i=this._restartStates).call(i,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(t));"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE,t);}},i=()=>{"disconnected"!==e.iceConnectionState&&"checking"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),jC.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},n=RC("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout(()=>{if(RC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&IA().supportPCSetConfiguration)t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);else if(wg())t(cv.UDP),this._restartTimer=window.setTimeout(i,4e3);else {if(t(cv.TCP),IA().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout(()=>{t(cv.RELAY),this._restartTimer=window.setTimeout(i,n);},n));this._restartTimer=window.setTimeout(i,n);}},800));}}else {if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{if("disconnected"===e.iceConnectionState&&RC("ICE_RESTART")){"CONNECTED"===AT(this,hv.QueryClientConnectionState)&&this.emit(hv.RequestRestartICE);}},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect());},4e3);"failed"===t&&(jC.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout(()=>this.emit(hv.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect());}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),eI.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:pT.TRACER}).onSuccess(),this.emit(hv.IceConnectionStateChange,e);},e.onICETransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"));},e.onDTLSTransportStateChange=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"));},e.onDTLSTransportError=e=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"));},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(qA.FIRST_FRAME_DECODED),eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_DECODE,qC.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}));},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_AUDIO_RECEIVED,qC.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i);},e.onFirstVideoReceived=e=>{var t;const i=Array.from(ph(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&eI.firstRemoteFrame(this.store.sessionId,YC.FIRST_VIDEO_RECEIVED,qC.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId});},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(hv.ConnectionTypeChange,i),jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onSelectedRemoteCandidateChanged=(e,t)=>{jC.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(Ay(t))," -> ").concat(JSON.stringify(Ay(e)),")"));},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0);};}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0;}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive||t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n&&(t.push(n),n[0]===lv.LocalVideoTrack)){const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}return t;}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(lv.LocalAudioTrack);if(e instanceof ew&&(null==i?void 0:i.track)instanceof nw)return i.track.isActive&&t.push([lv.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i;});if(n)if(n[0]===lv.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(lv.LocalVideoLowTrack);e&&t.push([lv.LocalVideoLowTrack,e]);}else t.push(n);return t;}createMuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}createUnmuteMessage(e){return e.map(e=>{var t;let i,[n,{track:r,ssrcs:s,id:o}]=e;switch(n){case lv.LocalAudioTrack:i=JI.Audio;break;case lv.LocalVideoTrack:i=bn(t=r._hints).call(t,jA.SCREEN_TRACK)?JI.Screen:JI.High;break;case lv.LocalVideoLowTrack:i=JI.Low;}return {stream_type:i,ssrcs:s,mid:o};});}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}]);}else Array.from(n.entries()).forEach(t=>{let[n,r]=t;i.push([e,{kind:n,id:r}]);});return i;}filterTobeUnSubscribedDataChannels(e,t){const i=[];return t.forEach(t=>{var n;null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.has(t.id)&&i.push(t);}),i;}createUnsubscribeMessage(e){const t=[];return e.forEach(e=>{let[i,{kind:n,id:r}]=e;switch(n){case av.VIDEO:return void(i._videoSSRC&&t.push({stream_type:av.VIDEO,ssrcId:i._videoSSRC}));case av.AUDIO:return void(i._audioSSRC&&t.push({stream_type:av.AUDIO,ssrcId:i._audioSSRC}));}}),t;}createUnsubscribeAllMessage(e){const t=new Map();return e.forEach(e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===av.VIDEO?e|=ZI.Video:e|=ZI.Audio,t.set(i,e);}else n===av.VIDEO?t.set(i,ZI.Video):t.set(i,ZI.Audio);}),{users:Array.from(t.entries()).map(e=>{let[t,i]=e;return {stream_id:t.uid,stream_type:i};})};}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t));});}async updateBitrateLimit(e){const t=this.localTrackMap.get(lv.LocalVideoTrack),i=this.localTrackMap.get(lv.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink)),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}));}isP2PDisconnected(){if(this.connection){return "connected"!==this.connection.peerConnectionState;}return !0;}mapPubResToRemoteConfig(e,t){return e.map((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find(e=>{let{stream_type:t}=e;return r===t;}))||void 0===n?void 0:n.attributes;});}async tryToUnmuteAudio(e){for(let i=0;i{let[,{id:t}]=e;return t;})));const r=this.createUnmuteMessage(n);return void(await yT(this,hv.RequestUnmuteLocal,r));}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return !(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e));},this.statsUploader.requestUpload=(e,t)=>this.emit(hv.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(hv.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks();}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0;}async requestReconnect(){this.dtlsFailedCount+=1,await iS(mS(this.dtlsFailedCount,ES)),this.emit(hv.RequestReconnect);}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&(await vT(this,hv.RequestUnpublishForReconnectPC,t)),this.disconnectForReconnect(),this.emit(hv.RequestReconnectPC);}canPublishLowStream(){return this.localTrackMap.has(lv.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof Rw);}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof Rw).length>1)throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof ew).length>1&&(e.some(e=>e instanceof ew&&e._bypassWebAudio)||!IA().webAudioMediaStreamDest))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof Rw&&this.pendingLocalTracks.some(e=>e instanceof Rw))throw new Kg(Hg.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof ew&&this.pendingLocalTracks.some(e=>e instanceof ew)&&(!IA().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof ew&&e._bypassWebAudio)))throw new Kg(Hg.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");}}getLowVideoTrack(e,t){const i=!RC("DISABLE_DUAL_STREAM_USE_ENCODING")&&IA().supportDualStreamEncoding,n=sF(sF({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Gx(e,n);const s=nS(8,"track-low-"),o=new Rw(r,sF(sF({},i&&{scaleResolutionDownBy:yy(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,s);return o.on(KA.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,GA.LOW_STREAM);}),o._hints.push(jA.LOW_STREAM),e.on("sei-to-send",e=>{o.emit("sei-to-send",e);}),e.addListener(BA.NEED_CLOSE,()=>{o.close();}),o;}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock");}async reportPCStats(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof jV){var r,s,o,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:u}=this.connection,{local:h,remote:p}=await this.connection.getSelectedCandidatePair();eI.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:u,intSucc:t?1:2,error:n,selectedLocalCandidateProtocol:null!==(r=null==h?void 0:h.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(s=h.candidateType)&&void 0!==s?s:"",selectedLocalCandidateAddress:"".concat(h.address,":").concat(h.port),selectedRemoteCandidateProtocol:null!==(o=p.protocol)&&void 0!==o?o:"",selectedRemoteCandidateType:null!==(a=p.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i});}}reportVideoFirstFrameDecoded(e,t,i,n){var r;const s=Array.from(ph(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(s){n||this.store.subscribe(s.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,o=r.subscribe.find(e=>e.userId===s.uid&&"video"===e.type);eI.firstRemoteVideoDecode(this.store.sessionId,YC.FIRST_VIDEO_DECODE,qC.FIRST_VIDEO_DECODE,{peer:s._uintid,videowidth:t,videoheight:i,subscribeElapse:RU.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==o?void 0:o.subscribeEnd)||0,subscriberStart:(null==o?void 0:o.subscribeStart)||0,videoAddNotify:(null==o?void 0:o.streamAdded)||0,state:n?1:0});}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return !1;const n=this.remoteUserMap.get(e);if(!n)return !1;const r=n.get(t);if(!r)return !1;const s=await this.connection.getRemoteSSRC(r);return void 0!==s&&s!==i;}resetConnection(e){jC.debug("[".concat(this.store.clientId,"] [P2PChannel] reset connection to ").concat(e)),this.state===uv.Connected?(jC.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===$I.datachannel?new iF({},this.store):this.isPlanB?new LV({},this.store):new jV({},this.store),this.bindConnectionEvents(this.connection)));}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===lv.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,GA.LOW_STREAM):i._updateRtpTransceiver(void 0);});}reportPCDisconnectedOrFailed(e){this.connection&&this.connection instanceof jV&&("disconnected"!==this.connection.iceConnectionState&&"checking"!==this.connection.iceConnectionState&&"failed"!==this.connection.iceConnectionState||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===dv.TCP_RESTART&&e===cv.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,dv.DISCONNECTED_OR_FAILED)));}}function dF(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,s=new Array(r),o=0;o>>3){case 0:break e;case 1:t.code=kF(e);break;case 2:t.msg=bF(e,kF(e));break;case 3:{let i=_F(e);t.data=hF(e),e.limit=i;break;}default:EF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function hF(e){let t={};e:for(;!vF(e);){let i=kF(e);switch(i>>>3){case 0:break e;case 1:t.requestId=bF(e,kF(e));break;case 2:t.requestType=kF(e)>>>0;break;case 3:t.scorePorn=PF(e);break;case 4:t.scoreSexy=PF(e);break;case 5:t.scoreNeutral=PF(e);break;case 6:t.requestScene=kF(e)>>>0;break;case 7:t.scene=kF(e)>>>0;break;default:EF(e,7&i);}}return t;}function pF(e,t){let i=e.service;void 0!==i&&(MF(t,8),MF(t,i));let n=e.vendor;void 0!==n&&(MF(t,16),MF(t,n));let r=e.token;void 0!==r&&(MF(t,26),wF(t,r));let s=e.callbackUrl;void 0!==s&&(MF(t,34),wF(t,s));}function _F(e){let t=kF(e),i=e.limit;return e.limit=e.offset+t,i;}function EF(e,t){switch(t){case 0:for(;128&NF(e););break;case 2:IF(e,kF(e));break;case 5:IF(e,4);break;case 1:IF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],cF.prototype,"startP2PConnection",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"connect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",void 0)],cF.prototype,"updateRemoteRTPCapabilities",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object,Object,Array,Object,String,String]),PI("design:returntype",cg)],cF.prototype,"preConnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"publishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublish",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"unpublishDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"unpublishLowStream",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"subscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number,Number,Array]),PI("design:returntype",cg)],cF.prototype,"subscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massSubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Boolean]),PI("design:returntype",cg)],cF.prototype,"unsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,Array]),PI("design:returntype",cg)],cF.prototype,"unsubscribeDataChannel",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],cF.prototype,"massUnsubscribe",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"muteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"unmuteRemote",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String]),PI("design:returntype",cg)],cF.prototype,"hasRemoteMediaWithLock",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],cF.prototype,"disconnectForReconnect",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],cF.prototype,"updateBitrateLimit",null),DI([dF,PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],cF.prototype,"remoteMediaSsrcChanged",null);let mF=new Float32Array(1);new Uint8Array(mF.buffer);let fF=new Float64Array(1),gF=new Uint8Array(fF.buffer);function TF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let SF=[];function RF(){const e=SF.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0};}function CF(e){SF.push(e);}function IF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function vF(e){return e.offset>=e.limit;}function yF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function AF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function bF(e,t){let i=AF(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function wF(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function OF(e,t){let i=yF(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,s=t.limit;e>>=0;t>=128;)DF(e,127&t|128),t>>>=7;DF(e,t);}function UF(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=yF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}function xF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}const VF=new Map([["moderation",1],["supervise",2]]);class FF extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(mv.CONNECTION_STATE_CHANGE,t,e);}get inspectType(){return this._inspectType;}set inspectType(e){var t;this._inspectMode=BT(t=e.map(e=>VF.get(e)||0)).call(t,(e,t)=>e+t),this._inspectType=e;}get quality(){return this._quality;}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this.qualityRatio;},6e4));}constructor(e){super(),sh(this,"name","AgoraRTCVideoContentInspect"),sh(this,"_connectionState",_v.CONNECTING),sh(this,"_innerConnectionState",void 0),sh(this,"sequence",0),sh(this,"inspectStartTime",void 0),sh(this,"workerManagerConnection",void 0),sh(this,"workerConnection",void 0),sh(this,"workerMessageLengthLimit",void 0),sh(this,"inspectIntervalMinimum",void 0),sh(this,"qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"wmSequence",0),sh(this,"inspectInterval",void 0),sh(this,"inspectTimer",null),sh(this,"ossFilePrefix",void 0),sh(this,"extraInfo",void 0),sh(this,"_inspectType",void 0),sh(this,"_inspectMode",void 0),sh(this,"_quality",1),sh(this,"qualityTimer",null),sh(this,"_inspectId",void 0),sh(this,"_needWorkUrlOnly",!1),sh(this,"inspectImage",()=>{if(this.connectionState!==_v.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval(()=>{this.connectionState===_v.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState);},this.inspectInterval{this._innerConnectionState=e,jC.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Ev[e]," ").concat(t||""));}),this.handleWorkerManagerEvents(),this.workerConnection=new zv("worker-"+this._inspectId,ES),this.handleWorkerEvents();}async init(e,t){this.emit(mv.STATE_CHANGE,Ev.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(mv.CONNECTION_STATE_CHANGE,(e,t)=>{t===_v.CONNECTED&&n();}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e);}).catch(e=>{r(e);});});}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=RC("VIDEO_INSPECT_WORKER_MANAGER_PORT");return {addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return "wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i);}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,responseTime:p};},(t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(mv.STATE_CHANGE,Ev.AP_CONNECTED);const{addressList:s}=r;return this.wmSequence++,s;}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4);}async connectWorker(e){await this.workerConnection.init([e]);}handleWorkerManagerEvents(){this.workerManagerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.20.2",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0);}),this.workerManagerConnection.on(SI.CLOSED,()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(mv.STATE_CHANGE,Ev.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw jC.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new LI(Hg.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw jC.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new LI(Hg.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=RC("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(mv.STATE_CHANGE,Ev.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(mv.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n);}}),this.workerManagerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{i(e);}),this.workerManagerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t);});}handleWorkerEvents(){this.workerConnection.on(SI.CONNECTED,async()=>{this.emit(mv.STATE_CHANGE,Ev.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=_v.CONNECTED;}),this.workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const i=uF(new Uint8Array(e.data));if(RC("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&jC.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(mv.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=BT(t=Object.keys(e)).call(t,(t,i)=>e[t]>e[i]?t:i,"porn"),r=Object.keys(e).find(e=>e===n);this.emit(mv.INSPECT_RESULT,r);}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"));}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,i.code+"",i.msg));}else jC.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.UNEXPECTED_RESPONSE,"invalid worker message type"));}),this.workerConnection.on(SI.CLOSED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.FAILED,()=>{this.connectionState=_v.CLOSED;}),this.workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===_v.CONNECTED?_v.RECONNECTING:_v.CONNECTING;}),this.workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this.workerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(mv.REQUEST_NEW_WORKER_URL,t=>{e([t]);}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e=>{this.connectWorkerManager(e,!0);}).catch(e=>{t(e);});});}static intToLong(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}async requestToInspectImage(){this.sequence++;const e=AT(this,mv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0);}else this.emit(mv.INSPECT_RESULT,void 0,new LI(Hg.INVALID_OPERATION,"Only the track being published can be inspected"));}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:FF.intToLong(Number(c-this.inspectStartTime)),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this.sequence,sid:o,timestamp:FF.intToLong(c),uid:a,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=lF(h);if(p.byteLength>>3){case 0:break e;case 1:t.code=eB(e);break;case 2:t.msg=XF(e,eB(e));break;case 3:t.requestId=XF(e,eB(e));break;case 4:t.timestamp=iB(e,!1);break;default:GF(e,7&i);}}return t;}({bytes:t=e,offset:0,limit:t.length});var t;}function GF(e,t){switch(t){case 0:for(;128&ZF(e););break;case 2:KF(e,eB(e));break;case 5:KF(e,4);break;case 1:KF(e,8);break;default:throw new Error("Unimplemented type: "+t);}}function WF(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}let HF=[];function KF(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t;}function YF(e){return e.offset>=e.limit;}function qF(e,t){let i=e.bytes,n=e.offset,r=e.limit,s=n+t;if(s>i.length){let t=new Uint8Array(2*s);t.set(i),e.bytes=t;}return e.offset=s,s>r&&(e.limit=s),n;}function zF(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i;}function JF(e,t){let i=qF(e,t.length);e.bytes.set(t,i);}function XF(e,t){let i=zF(e,t),n=String.fromCharCode,r=e.bytes,s="�",o="";for(let e=0;e=t?o+=s:(a=r[e+i+1],128!=(192&a)?o+=s:(l=(31&u)<<6|63&a,l<128?o+=s:(o+=n(l),e++))):224==(240&u)?e+2>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?o+=s:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?o+=s:(o+=n(l),e+=2))):240==(248&u)?e+3>=t?o+=s:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?o+=s:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?o+=s:(l-=65536,o+=n(55296+(l>>10),56320+(1023&l)),e+=3))):o+=s;}return o;}function QF(e,t){let i=t.length,n=0;for(let e=0;e=55296&&r<=56319&&e+1=55296&&n<=56319&&e+1>6&31|192:(n<65536?s[r++]=n>>12&15|224:(s[r++]=n>>18&7|240,s[r++]=n>>12&63|128),s[r++]=n>>6&63|128),s[r++]=63&n|128);}}function ZF(e){return e.bytes[zF(e,1)];}function $F(e,t){let i=qF(e,1);e.bytes[i]=t;}function eB(e){let t,i=0,n=0;do{t=ZF(e),i<32&&(n|=(127&t)<>>=0;t>=128;)$F(e,127&t|128),t>>>=7;$F(e,t);}function iB(e,t){let i,n=0,r=0,s=0;return i=ZF(e),n=127&i,128&i&&(i=ZF(e),n|=(127&i)<<7,128&i&&(i=ZF(e),n|=(127&i)<<14,128&i&&(i=ZF(e),n|=(127&i)<<21,128&i&&(i=ZF(e),r=127&i,128&i&&(i=ZF(e),r|=(127&i)<<7,128&i&&(i=ZF(e),r|=(127&i)<<14,128&i&&(i=ZF(e),r|=(127&i)<<21,128&i&&(i=ZF(e),s=127&i,128&i&&(i=ZF(e),s|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|s<<24,unsigned:t};}function nB(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,s=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,o=qF(e,s),a=e.bytes;switch(s){case 10:a[o+9]=r>>>7&1;case 9:a[o+8]=9!==s?128|r:127&r;case 8:a[o+7]=8!==s?n>>>21|128:n>>>21&127;case 7:a[o+6]=7!==s?n>>>14|128:n>>>14&127;case 6:a[o+5]=6!==s?n>>>7|128:n>>>7&127;case 5:a[o+4]=5!==s?128|n:127&n;case 4:a[o+3]=4!==s?i>>>21|128:i>>>21&127;case 3:a[o+2]=3!==s?i>>>14|128:i>>>14&127;case 2:a[o+1]=2!==s?i>>>7|128:i>>>7&127;case 1:a[o]=1!==s?128|i:127&i;}}const rB={},sB={},oB=4294967296,aB=oB*oB,cB=aB/2,dB=_B(0,!0),lB=_B(0),uB=EB(0,-2147483648,!1),hB=EB(-1,2147483647,!1),pB=EB(-1,-1,!0);function _B(e,t){let i,n,r;return t?(r=0<=(e>>>=0)&&e<256)&&(n=sB[e],n)?n:(i=EB(e,0,!0),r&&(sB[e]=i),i):(r=-128<=(e|=0)&&e<128)&&(n=rB[e],n)?n:(i=EB(e,e<0?-1:0,!1),r&&(rB[e]=i),i);}function EB(e,t,i){return {low:0|e,high:0|t,unsigned:!!i};}function mB(e,t){if(isNaN(e))return t?dB:lB;if(t){if(e<0)return dB;if(e>=aB)return pB;}else {if(e<=-cB)return uB;if(e+1>=cB)return hB;}return e<0?t?dB:lB:EB(e%oB|0,e/oB|0,t);}function fB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}class gB extends dT{get connectionState(){return this._connectionState;}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(Cv.CONNECTION_STATE_CHANGE,e,t);}get quality(){return this._quality;}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this._qualityRatio;},6e4));}constructor(e){var t;super(),sh(this,"name","AgoraRTCImageModeration"),sh(this,"_connectionState",Rv.CONNECTING),sh(this,"_sequence",0),sh(this,"_moderationStartTime",void 0),sh(this,"_workerConnection",void 0),sh(this,"_workerMessageLengthLimit",void 0),sh(this,"_qualityRatio",void 0),sh(this,"_connectInfo",void 0),sh(this,"_cancelTokenSource",sC.CancelToken.source()),sh(this,"_retryConfig",void 0),sh(this,"_moderationInterval",void 0),sh(this,"_moderationTimer",null),sh(this,"_moderationMode",1),sh(this,"_quality",1),sh(this,"_qualityTimer",null),sh(this,"_ticket",void 0),sh(this,"_moderationIntervalMinimum",void 0),sh(this,"_uploadFailedNum",0),sh(this,"_uploadNum",0),sh(this,"_uploadTimer",null),sh(this,"_extraInfo",void 0),sh(this,"_vendor",""),sh(this,"_encoder",new TextEncoder()),sh(this,"_moderationId",void 0),sh(this,"inspectImage",()=>{if(this.connectionState!==Rv.CONNECTED)throw new LI(Hg.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval(()=>{this.connectionState===Rv.CONNECTED?this.requestToInspectImage():jC.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState);},this._moderationInterval{jC.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Iv[e]," ").concat(t||""));}),this.handleWorkerEvents();}async init(e,t){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new cg((n,r)=>{this.on(Cv.CONNECTION_STATE_CHANGE,(e,t)=>{e===Rv.CONNECTED&&n();}),this.requestAP(e,i,t).then(e=>{this.connectWorker(e);}).catch(e=>{r(e);});});}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),jC.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===Rv.CONNECTED&&this.inspectImage();}async requestAP(e,t,i){const n=RC("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:s,cname:o,sid:a,token:c,uid:d}=t;cA++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:s,cname:o,command:"allocateEdge",requestId:cA,seq:cA,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return fS(async()=>{h=Date.now();const e=await By(_,{data:u,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw jC.error(t.toString()),t;}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}if(!t.servers.some(e=>!!e.wss)){const e=new LI(Hg.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw jC.error(e.toString()),e;}const n=RC("IMAGE_MODERATION_WORKER_HOST");return {addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return "wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation");}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p};},(t,i)=>(eI.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(eI.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==Hg.OPERATION_ABORTED&&t.code!==Hg.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n);}(n,e,t,i);this.emit(Cv.STATE_CHANGE,Iv.AP_CONNECTED);const{addressList:s,ticket:o}=r;return this._ticket=o,s;}async connectWorker(e){this.emit(Cv.STATE_CHANGE,Iv.CONNECT_WORKER),await this._workerConnection.init(e,1e4);}handleWorkerEvents(){this._workerConnection.on(SI.CONNECTED,async()=>{this.emit(Cv.STATE_CHANGE,Iv.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Rv.CONNECTED;}),this._workerConnection.on(SI.CLOSED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.FAILED,()=>{this.connectionState=Rv.CLOSED;}),this._workerConnection.on(SI.RECONNECTING,()=>{this.connectionState=this.connectionState===Rv.CONNECTED?Rv.RECONNECTING:Rv.CONNECTING;}),this._workerConnection.on(SI.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const t=jF(new Uint8Array(e.data));RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,jC.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{eI.reportApiInvoke(this._connectInfo.sid||null,{name:hT.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:pT.TRACER}).onError(new LI(Hg.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null;},RC("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))));}else jC.error("[".concat(this._moderationId,"] Unexpected message type from worker"));}),this._workerConnection.on(SI.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext");}),this._workerConnection.on(SI.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t);});}static intToLong(e){return {low:e|=0,high:e>>31,unsigned:e>=0};}async requestToInspectImage(){const e=AT(this,Cv.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0);}else RC("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&jC.debug("Only the track being published can be inspected");}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:s,sid:o,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await gw(d,i,n),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+nS(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:gB.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.20.2",sequence:this._sequence,sid:o,timestamp:mB(c),uid:a,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=BF(h);if(p.byteLength0&&(n.firstRecvTs=Date.now()-s);let a=i.mediaDelay+o;a<=0?(t.pop(),AB(i.context,r),a=0):a=Math.min(a,CB),setTimeout(()=>t.length&&yB(e),a);}function AB(e,t){e.safeEmit(mT.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t);}function bB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return AB(i,{uid:e.uid,payload:e.payload});const n="".concat(i.id,"-").concat(e.uid),r=IB.get(n)||[],s=r.findIndex(t=>e.sendTs>=t.sendTs),o=SB(SB({},e),{},{context:i,mediaDelay:t,recvTs:Date.now()});-1===s?r.push(o):r.splice(s,0,o),IB.set(n,r);let a=!1;var c;vB.has(n)?a=!(null===(c=vB.get(n))||void 0===c||!c.isSyncing):vB.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||yB(n);}const wB=Sg().name;function OB(){return !function(e,t,i){const n=Sg();if(n.os!==_g.IOS||!n.osVersion)return !1;const r=n.osVersion.split(".");return i?t&&Number(r[0])===e&&Number(r[1]){this.publish(e,!1).then(t).catch(i);}),sh(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i);}),sh(this,"_handleUserOnline",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return void jC.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&jC.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find(t=>t.uid===e.uid);if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(mT.USER_JOINED,t));else {const t=new sV(e.uid,e.uint_id||e.uid);this._users.push(t),jC.debug("[".concat(this._clientId,"] user online"),e.uid),this.safeEmit(mT.USER_JOINED,t);}}),sh(this,"_handleUserOffline",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:WT(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),jC.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(mT.USER_LEAVED,t,e.reason));}),sh(this,"_handleAddAudioOrVideoStream",(e,t,i,n,r,s,o)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(t,this.channelName))return;const a=this._users.find(e=>e.uid===t);if(!a)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));jC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==n&&(a._cname=n),s&&(a._audioOrtc=s)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==o&&(a._rtxSsrcId=o),s&&(a._videoOrtc=s)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(jC.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.safeEmit(mT.USER_PUBLISHED,a,e)),"video"===e?eI.onGatewayStream(this._sessionId,YC.ON_ADD_VIDEO_STREAM,qC.ON_ADD_VIDEO_STREAM,{peer:r||t,ssrc:a._videoSSRC}):eI.onGatewayStream(this._sessionId,YC.ON_ADD_AUDIO_STREAM,qC.ON_ADD_AUDIO_STREAM,{peer:r||t,ssrc:a._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then(t=>{if(t&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof cF))return this._p2pChannel.unsubscribe(a,e,!0).then(()=>this._subscribe(a,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),sh(this,"_handleRemoveStream",e=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);if(!t)return void jC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));jC.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"audio"),jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"video");}:t.hasVideo?i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"video");}:t.hasAudio&&(i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(mT.USER_UNPUBLISHED,t,"audio");}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof cF&&this._p2pChannel.unsubscribe(t).then(e=>{if(e)return this._gateway.unsubscribe(e,t.uid);}),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),eI.onGatewayStream(this._sessionId,YC.ON_REMOVE_STREAM,qC.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i();}),sh(this,"_handleSetStreamLocalEnable",(e,t,i)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(t,this.channelName))return;const n=this._users.find(e=>e.uid===t);if(!n)return void jC.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));jC.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";jC.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e);}}else {n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(mT.USER_INFO_UPDATED,t,e);}}const s="audio"===e?n.hasAudio:n.hasVideo;return r!==s?!r&&s?(jC.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(mT.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),jC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(mT.USER_UNPUBLISHED,n,e)):void 0;}),sh(this,"_handleMuteStream",(e,t,i)=>{if(RC("BLOCK_LOCAL_CLIENT")&&sI(e,this.channelName))return;jC.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find(t=>t.uid===e);if(!n)return void jC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t);}}else {n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";jC.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(mT.USER_INFO_UPDATED,e,t);}}const s="audio"===t?n.hasAudio:n.hasVideo;if(r!==s){if(!r&&s){return ("audio"===t?n._audioSSRC:n._videoSSRC)?(jC.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(mT.USER_PUBLISHED,n,t)):void jC.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."));}"video"===t&&n._videoTrack&&!n._video_pre_subscribed&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),jC.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(mT.USER_UNPUBLISHED,n,t);}}),sh(this,"_handleP2PLost",async e=>{jC.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():jC.warning("[".concat(this._clientId,"] P2PLost stream not found"),e);}),sh(this,"_handleTokenWillExpire",()=>{jC.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_WILL_EXPIRE);}),sh(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),jC.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")));}),sh(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(mT.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(mT.NETWORK_QUALITY,e);}),sh(this,"_handleP2PAddAudioOrVideoStream",(e,t,i,n)=>{const r=this._users.find(e=>e.uid===t);if(!r)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));jC.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const s="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==i&&(r._audioSSRC=i),void 0!==n&&(r._audioMid=n)):(r._video_added_=!0,void 0!==i&&(r._videoSSRC=i),void 0!==n&&(r._videoMid=n)),("audio"===e?r.hasAudio:r.hasVideo)&&!s&&(jC.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(mT.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(jC.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe error"),e.toString());}));}),this._config=e,this._clientId=nS(5,"client-"),this.store=new AC(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),jC.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(EC," build: ").concat(gC,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{IT(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions);}catch(e){jC.warning("[".concat(this._clientId,"] ").concat(e.toString()));}this._statsCollector=new mV(this.store),this._statsCollector.onStatsException=(e,t,i)=>{jC.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.safeEmit(mT.EXCEPTION,{code:e,msg:t,uid:i});},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find(t=>t.uid===e);r&&eI.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid});},this.store.useDataChannel=IA().supportDataChannel&&RC("SIGNAL_CHANNEL"),this.store.useP2P="p2p"===e.mode,this._gateway=new xy(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||ES,httpRetryConfig:e.httpRetryConfig||ES,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._configDistribute=new RA(),this.store.useP2P?(this._p2pChannel=new hV(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new cF(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents();}async joinMeta(e,t,i,n,r){let s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=arguments.length>6&&void 0!==arguments[6]&&arguments[6];SC("JOIN_GATEWAY_USE_443PORT_ONLY",s),SC("JOIN_GATEWAY_USE_DUAL_DOMAIN",o);const a=this._gateway.signal.websocket;return a instanceof qv&&(a.use443PortOnly=s,a.tryDoubleDomain=o),async function(e,t,i){ug.get(e)||ug.set(e,[]),hg.get(e)||hg.set(e,t),pg.get(e)||pg.set(e,0);const n=ug.get(e),r=hg.get(e);if(!n||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(pg.get(e)===r){const e=lg();n.push(e),await e.promise;}pg.set(e,pg.get(e)+1);for(var s=arguments.length,o=new Array(s>3?s-3:0),a=3;a0&&(n[0].resolve(),n.shift()),0===pg.get(e)&&(ug.set(e,[]),hg.set(e,0),pg.set(e,0)),c;}("client.join",RC("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,n,r);}async join(e,t,i,n,r){const s=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const o=pC(),a=_C()?window.isSecureContext:"Browser Not Support";if(!_C()&&!o||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";jC.warning(e);}const c=rS();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),jC.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const d=eI.reportApiInvoke(c,{name:hT.JOIN,options:[e,t,i,n],states:{isHttps:o,isSecureContext:a},tag:pT.TRACER});eI.setAppId(e);try{if(!i&&null!==i)throw new LI(Hg.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Xg(i,"token",1,2047),Xg(e,"appid",1,2047),kI(t),n&&MI(n),r&&Xg(r,"optionalInfo",1,2047);}catch(e){throw d.onError(e),e;}if(jC.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._leaveMutex.isLocked){jC.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),jC.debug("[".concat(this._clientId,"] join: continue"));}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const e=new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw d.onError(e),e;}this._sessionId||(this._sessionId=c,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";const l=DB(DB({},this._rtmConfig),{},{clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(l.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(l.stringUid=n,this._uintUid?(l.uid=this._uintUid,this._uintUid=void 0):l.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(l.aesmode=this._encryptionMode,l.aespassword=await aT(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(l.aessalt=this._encryptionSalt);}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret){if(window.crypto.subtle){const e=new TextEncoder(),t=RC("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(l.appId+this._encryptionSecret+this._encryptionSecret):e.encode(l.appId+l.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,s=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:DC,hash:"SHA-256",salt:i},n,r+NC);return new Uint8Array(s).subarray(r/8);}(this._encryptionMode,t,XT(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){const n=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:DC,hash:"SHA-256",salt:i},n,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"]);}(this._encryptionMode,t,XT(this._encryptionSalt));}else a?jC.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):jC.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;}else this._encryptDataStream=!1,jC.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:l.stringUid});const u=this._sessionId;setTimeout(()=>{"CONNECTING"===this.connectionState&&u===this._sessionId&&eI.joinChannelTimeout(this._sessionId,5);},5e3);try{var h;let n;const r=l.cloudProxyServer;if(bn(h=["proxy3","proxy4","proxy5"]).call(h,r)){const e=RC("PROXY_SERVER_TYPE3");Array.isArray(e)?l.proxyServer=e[0]:l.proxyServer=e;}if(eI.setProxyServer(l.proxyServer),jC.setProxyServer(l.proxyServer),this.store.requestAPStart(),l.stringUid&&!l.uid){let e;[e,n]=await cg.all([pA(l.stringUid,l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store),hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store)]),jC.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(l.stringUid," => ").concat(e)),l.uid=e,n.gatewayInfo.uid=e,n.gatewayInfo.res.uid=e;}else n=await hA(l,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,!0,this.store);if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(l,this._axiosCancelSource.token),this._configDistribute.on(sv.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e);});},0),this._key=i||e;const s=n.gatewayInfo,o=l.uid?l.uid:s.uid;this._joinInfo=DB(DB({},l),{},{cid:s.cid,uid:o,vid:s.vid,apResponse:s.res,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs}),this.store.intUid=o;const a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));d.onSuccess(a),this._appId=e,this._channelName=l.cname,this._uid=a,this.store.uid=a,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(bg()?"beforeunload":"pagehide",this._handleBeforeUnload);},0);const c=l.stringUid?"string uid: ".concat(l.stringUid,",uid: ").concat(l.uid):"uid: ".concat(this._uid);return jC.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout(()=>{jC.startUpload();},5e3),this.store.joinEnd(),p=this,bn(rI).call(rI,p)||rI.push(p),a;}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===Hg.OPERATION_ABORTED?jC.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t):jC.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),t),t.code!==Hg.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),d.onError(t),t;}var p;}_joinGateway(){if(!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!RC("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then(e=>e).catch(e=>{if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;if(e.code===Hg.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,ET.FALLBACK),e;throw e;}).then(e=>{if(e instanceof LI){if(e.code===Hg.INIT_WEBSOCKET_TIMEOUT){if(jC.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const e=RC("PROXY_SERVER_TYPE3");if(Array.isArray(e)){if(this._joinInfo.apUrl){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(this._joinInfo.apUrl)[1].split("."),i=t.slice(t.length-2).join(".");e.forEach(e=>{this._joinInfo&&bn(e).call(e,i)&&(this._joinInfo.proxyServer=e);}),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=e[0]);}else this._joinInfo.proxyServer=e[0];}else this._joinInfo.proxyServer=e;const t=RC("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);t&&t[1]&&"443"!==t[1]&&jC.setProxyServer(this._joinInfo.proxyServer),"443"!==RC("STATS_COLLECTOR_PORT").toString()&&eI.setProxyServer(this._joinInfo.proxyServer);return eI.reportApiInvoke(this._sessionId,{name:hT.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),RC("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&this._joinInfo.turnServer.servers.forEach(e=>{"forceturn"in e&&(e.forceturn=!0);}),this._gateway.join(this._joinInfo,this._key);}if(jC.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new LI(Hg.INVALID_OPERATION);return eI.reportApiInvoke(this._sessionId,{name:hT.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:pT.TRACER}).onSuccess(),this._joinGateway();}return e;}).then(e=>e);}async leave(){jC.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(bg()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=rI.indexOf(e);-1!==t&&rI.splice(t,1);}(this);const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return jC.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),jC.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e();}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof lb))return this._publishDataChannel(e);e=[e];}if(0===e.length)throw new LI(Hg.INVALID_PARAMS,"param list is empty");const i=e;if("audience"===this._gateway.role)throw new LI(Hg.INVALID_OPERATION,"audience can not publish stream");for(const e of i){if(!(e instanceof lb))throw new LI(Hg.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new LI(Hg.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()));}jC.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))));const n=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach(e=>{const t=this._configDistribute.getBitrateLimit();e instanceof Rw&&t&&e.setBitrateLimit(t.uplink);});try{await this._publishHighStream(i),jC.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))));}catch(e){throw jC.error("[".concat(this._clientId,"] publish error"),e.toString()),e;}finally{n();}}async _publishDataChannel(e){zg(e.id,"id",0,65535,!0),Yg(e.ordered,"ordered"),Xg(e.metadata,"metadata",0,512),jC.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex(t=>t.id===e.id))throw new LI(Hg.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&RC("FORCE_TURN")&&!RC("TURN_ENABLE_TCP")&&!RC("TURN_ENABLE_UDP"))throw new LI(Hg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=new aP(e);if(await this._p2pChannel.publishDataChannel([i]),!this._p2pChannel.isP2PDisconnected()){if("number"!=typeof i._originDataChannelId)throw jC.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new LI(Hg.CREATE_DATACHANNEL_ERROR);try{const t={streamId:e.id,ordered:e.ordered,maxRetransmits:RC("DATASTREAM_MAX_RETRANSMITS"),metadata:e.metadata,channelId:i._originDataChannelId};await this._gateway.publishDataChannel(this._uid,t,!0),await i._waitTillOpen();}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e;}}return jC.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i;}catch(e){throw jC.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e;}finally{t();}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e){if(Array.isArray(e))t=e;else {if(!(e instanceof lb))return this._unpublishDataChannel([e]);t=[e];}}else this.store.useP2P||(await this._unpublishDataChannel()),t=this._p2pChannel.getAllTracks(!0);jC.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map(e=>"".concat(e.getTrackId()," "))," "));const i=await this._publishMutex.lock();try{if(this._p2pChannel instanceof hV){const e=await this._p2pChannel.unpublish(t);e&&(await this._gateway.sendExtensionMessage(vv.UNPUBLISH,{unpubMsg:e},!0));}else {const e=await this._p2pChannel.unpublish(t);e&&(await this._gateway.unpublish(e,this._uid)),jC.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map(e=>"".concat(e.getTrackId()))));}}catch(e){throw jC.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e;}finally{i&&i();}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),jC.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map(e=>"".concat(e.id," "))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublishDataChannel(e);i&&(await this._gateway.unpublishDataChannel(i)),jC.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map(e=>"".concat(e.id))));}catch(e){throw jC.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e;}finally{t&&t();}}async subscribe(e,t,i){return "datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t);}async presubscribe(e,t){if(qg(t,"mediaType",["audio","video"]),this._p2pChannel instanceof hV)throw new LI(Hg.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=t===av.AUDIO,n=t===av.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:s,ortc:o,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(null==s)throw new LI(Hg.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find(t=>t.uid===e);l||(l=new sV(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),i&&(l._audioSSRC=s,l._audio_pre_subscribed=!0,o&&(l._audioOrtc=o)),n&&(l._videoSSRC=s,l._video_pre_subscribed=!0,o&&(l._videoOrtc=o),null!=a&&(l._rtxSsrcId=a)),jC.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(s)),await this._p2pChannel.subscribe(l,t,s,a,o);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u;}catch(t){throw jC.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t;}finally{r();}}async _subscribeDataChannel(e,t){var i;if(zg(t,"channelId",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e))throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new LI(Hg.INVALID_REMOTE_USER,"user is not published");const n=null===(i=e._dataChannels)||void 0===i?void 0:i.find(e=>e.id===t);if(!n)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);const r=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&bn(t).call(t,n.id))try{var s;if("number"!=typeof n._originDataChannelId)throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new LI(Hg.CREATE_DATACHANNEL_ERROR);const t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!==(s=n.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen();}catch(t){if((null==t?void 0:t.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id);}return jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n;}finally{r();}}async _p2pSubscribe(e,t,i){if(qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t;}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not published");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t;}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i;}const n=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this._p2pChannel instanceof hV&&(await this._p2pChannel.subscribe(e,t,i,n));}catch(e){throw e;}jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set fallback failed"),e);});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user object");return i;}catch(t){throw jC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t;}finally{n();}}async _subscribe(e,t,i){if(this._p2pChannel instanceof hV)return this._p2pSubscribe(e,t);if(qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t;}if(!e.hasAudio&&!e.hasVideo){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not published");throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t;}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i;}let n="audio"===t?e._audioSSRC:e._videoSSRC,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?av.AUDIO:av.VIDEO,ssrcId:n};const a=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==n&&(n=i,r="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,o={stream_type:"audio"===t?av.AUDIO:av.VIDEO,ssrcId:n}),RU.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,s,r);try{await this._gateway.subscribe(e.uid,o,!0);}catch(i){if((null==i?void 0:i.code)!==Hg.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t);}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t);}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i;}jC.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set fallback failed"),e);});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new LI(Hg.UNEXPECTED_ERROR,"can not find remote track in user object");return i;}catch(t){throw jC.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t;}finally{a();}}async massSubscribe(e){if(Qg(e,"subscribeList"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map(),n=await this._subscribeMutex.lock();jC.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i);}).join("; ")));const r=(e=[...e]).map(e=>{let{user:t,mediaType:i}=e;return {user:t,mediaType:i};}),s=await this._p2pChannel.globalLock();try{var o;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:s,mediaType:o}=n;if(qg(o,"mediaType",["audio","video"]),!s){const e=new LI(Hg.INVALID_PARAMS,"user property does not exist in subscribeList item");throw jC.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e;}if(!this._users.find(e=>e===s)){const i=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");jC.error("[".concat(this._clientId,"] can not massSubscribe ").concat(s.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue;}if("audio"===o&&(!s.hasAudio||void 0===s._audioSSRC)||"video"===o&&(!s.hasVideo||void 0===s._videoSSRC)){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);jC.error("[".concat(this._clientId,"] can not subscribe ").concat(s.uid," with mediaType ").concat(o,", remote user is not published")),r[t].error=i,e.splice(t,1);continue;}const a=ZI.Video|ZI.LwoVideo,c=i.get(s);if(c){if("video"===o?c&a:c&ZI.Audio){e.splice(t,1),jC.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(s.uid,", mediaType:").concat(o," twice"));continue;}i.set(s,c|("video"===o?a:ZI.Audio));}else i.set(s,"video"===o?a:ZI.Audio);}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:s}=n,o=ZI.Video|ZI.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,s)){await this._p2pChannel.unmuteRemoteNoLock(r,s);const n=i.get(r);i.set(r,"video"===s?n^o:n^ZI.Audio),e.splice(t,1);}}this.store.massSubscribe(e.map(e=>({userId:e.user.uid,type:e.mediaType})),t);const a=BT(o=Array.from(i.entries())).call(o,(e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&ZI.Audio&&(r.audio_ssrc=i._audioSSRC),n&ZI.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),e;},[]);try{e.length>0&&(await this._p2pChannel.massSubscribeNoLock(e.map(e=>{let{user:t,mediaType:i}=e;return {user:t,mediaType:i,ssrcId:i===av.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===av.VIDEO?t._rtxSsrcId:void 0};})));const i=new Map();if(a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach(e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:s}=e;(n||r||s)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:s});});}if(Array.from(i.entries()).length>0){const e=[];Array.from(i.entries()).forEach(t=>{let[i,n]=t;const r=this.remoteUsers.find(e=>e.uid===i);if(r){let t;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=av.VIDEO:n.audio_error_code&&(t=av.AUDIO),e.push({user:r,mediaType:t});}}),e.length>0&&(await this._p2pChannel.massUnsubscribeNoLock(e));}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=kv(i);jC.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new LI(Hg.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc));}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack);}return this.store.massSubscribe(r.filter(e=>!e.error).map(e=>({userId:e.user.uid,type:e.mediaType})),void 0,Date.now()),r.forEach(e=>{var i;eI.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===av.VIDEO,audio:e.mediaType===av.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===av.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0);}),jC.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i);}).join("; "))),r;}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t;}}finally{s(),n();}}async unsubscribe(e,t,i){if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i);}else await this._unsubscribeDataChannel(e,i);if(t&&qg(t,"mediaType",["audio","video"]),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t;}jC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const n=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof hV)await this._p2pChannel.unsubscribe(e,t);else {const i=await this._p2pChannel.unsubscribe(e,t);i&&(await this._gateway.unsubscribe(i,e.uid)),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&WT(this._users,e),jC.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t));}}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning("disconnecting p2p, abort unsubscribe request.");throw jC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t;}finally{n();}}async _unsubscribeDataChannel(e,t){if(t&&zg(t,"id",0,65535,!0),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new LI(Hg.INVALID_REMOTE_USER,"user is not in the channel");throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t;}let i;if("number"==typeof t){const n=e._dataChannels.find(e=>e.id===t);n&&(i=[n]);}else i=e._dataChannels;if(void 0===i){const i=new LI(Hg.REMOTE_USER_IS_NOT_PUBLISHED);throw jC.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i;}jC.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map(e=>e.id)));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&(await this._gateway.unsubscribeDataChannel(t,e.uid)),jC.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t));}catch(t){if(t.code===Hg.DISCONNECT_P2P)return void jC.warning("disconnecting p2p, abort unsubscribe request.");throw jC.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t;}}async massUnsubscribe(e){if(Qg(e,"unsubscribeList"),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");jC.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";");}).join())),e=[...e];const t=new Map();for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new LI(Hg.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw jC.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e;}qg(r,"mediaType",["video","audio",void 0]);if(!this._users.find(e=>e===n)){jC.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue;}const s=ZI.Video|ZI.LwoVideo;if(t.has(n)){const o=t.get(n);let a;switch(r){case"video":a=o&s;break;case"audio":a=o&ZI.Audio;break;default:a=o&(ZI.Audio|s);}if(a){jC.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue;}r?"audio"===r?t.set(n,o|ZI.Audio):"video"===r&&t.set(n,o|s):t.set(n,o|ZI.Audio|s);}else r?"audio"===r?t.set(n,ZI.Audio):"video"===r&&t.set(n,s):t.set(n,ZI.Audio|s);}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&(await this._gateway.massUnsubscribe(t)),jC.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return "user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";");}).join()));}catch(e){if(e.code===Hg.DISCONNECT_P2P)return void jC.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw jC.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e;}}async setLowStreamParameter(e){!function(e){if(!e)throw new Kg(Hg.INVALID_PARAMS);Zg(e.width)||Jg(e.width,"streamParameter.width"),Zg(e.height)||Jg(e.height,"streamParameter.height"),Zg(e.framerate)||Jg(e.framerate,"streamParameter.framerate"),Zg(e.bitrate)||zg(e.bitrate,"streamParameter.bitrate");}(e),(!e.width&&e.height||e.width&&!e.height)&&jC.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),jC.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0;}getNtpWallTimeInMs(){return "visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset;}setProxyServer(e,t){if(Xg(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");}this._proxyServer=e,eI.setProxyServer(this._proxyServer),jC.setProxyServer(this._proxyServer),jC.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."));}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");}if(RT(e))return this._turnServer={servers:e,mode:"original-manual"},void jC.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>CT(e)),this._turnServer={servers:e,mode:"manual"},jC.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."));}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new LI(Hg.INVALID_OPERATION,"you should set license before join channel");}if(Xg(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new LI(Hg.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,jC.info("[".concat(this._clientId,"] set license success"),e);}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new LI(Hg.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new LI(Hg.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new LI(Hg.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")));}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,jC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode);}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"Stop proxy server after leave channel");eI.setProxyServer(),jC.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",jC.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]};}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new LI(Hg.INVALID_PARAMS,"accessPoints is required.");Qg(e.accessPoints.serverList,"accessPoints.serverList"),Xg(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{zg(e,t,0,65535,!0);};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");RC("CLOSE_AFB_FOR_LOCAL_AP")&&(SC("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),SC("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,s=e.accessPoints.serverList.map(e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e),o=s.map(e=>"".concat(e,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,SC("WEBCS_DOMAIN",o),SC("WEBCS_DOMAIN_BACKUP_LIST",o),SC("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Qg(e.report.hostname,"report.hostname"),SC("EVENT_REPORT_DOMAIN",e.report.hostname[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(SC("EVENT_REPORT_DOMAIN",s[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",s[1]||s[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),SC("STATS_COLLECTOR_PORT",a),e.report?SC("ENABLE_EVENT_REPORT",!0):SC("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Qg(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=s[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),SC("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Qg(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=s;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),SC("CDS_AP",l.map(e=>"".concat(e,":").concat(u))),e.cds?SC("ENABLE_CONFIG_DISTRIBUTE",!0):SC("ENABLE_CONFIG_DISTRIBUTE",!1),jC.info("set local access point v2 success");}setLocalAccessPoints(e,t){if(Qg(e,"serverList"),Xg(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new LI(Hg.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map(e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,SC("WEBCS_DOMAIN",e),SC("WEBCS_DOMAIN_BACKUP_LIST",e),SC("GATEWAY_DOMAINS",[t]),SC("EVENT_REPORT_DOMAIN",e[0]),SC("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),SC("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),jC.info("[".concat(this._clientId,"] set local access point success"));}async setRemoteDefaultVideoStreamType(e){if(qg(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType;}catch(e){throw jC.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e;}else jC.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e));}async setRemoteVideoStreamType(e,t){qg(t,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout(()=>{const t=this._users.find(t=>t.uid===e);t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution();},2e3);}catch(e){throw jC.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e;}jC.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t);}async setStreamFallbackOption(e,t){qg(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t);}catch(e){throw jC.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e;}jC.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t);}setEncryptionConfig(e,t,i,n){!function(e){qg(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"]);}(e),Xg(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(bn(r).call(r,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new LI(Hg.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes");}else if(i)throw new LI(Hg.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Yg(n,"encryptDataStream"),!bn(r).call(r,e))throw new LI(Hg.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0;}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||jC.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=QT(i));}async renewToken(e){if(Xg(e,"token",1,2047),!this._key||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(RC("USE_NEW_TOKEN")){jC.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await gA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES);jC.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t});}else jC.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});jC.debug("[".concat(this._clientId,"] renewToken success"));}catch(e){throw this._key=t,this._joinInfo.token=t,jC.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e;}finally{i();}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?jC.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(mT.VOLUME_INDICATOR,e);},RC("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3);}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e;}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new LI(Hg.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming");}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new LI(Hg.LIVE_STREAMING_TASK_CONFLICT);const i=t?RI.TRANSCODE:RI.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i);}setLiveTranscoding(e){return this._createLiveStreamingClient(RI.TRANSCODE).setTranscodingConfig(e);}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new LI(Hg.INVALID_PARAMS,"can not find live streaming url to stop");await cg.all(t.map(t=>t&&t.stopLiveStreamingTask(e)));}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const i=this._createLiveStreamingClient(RI.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,RI.INJECT);}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(RI.INJECT),i=Array.from(NI(e=t.streamingTasks).call(e)).find(e=>e.mode===RI.INJECT);if(!this._joinInfo||!i)throw new LI(Hg.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url);}async startChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e);}async updateChannelMediaRelay(e){vV(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e);}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0);}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder();e.payload=t.encode(e.payload);}let n=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(n=!0,e.payload=await async function(e,t,i){var n;const r=BT(n=Array.from(i)).call(n,(e,t)=>e+t,0),s={serverTs:0,seq:LC++,length:i.length,checkSum:r},o=new Uint8Array(lS(r,2)),a=new ArrayBuffer(PC),c=new DataView(a);c.setUint32(0,s.serverTs),c.setUint16(4,s.seq),c.setUint16(6,s.length),c.setUint16(8,s.checkSum);const d=16-i.length%16;i=ZT(i,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:OC,additionalData:o},t,i);return ZT(new Uint8Array(a),new Uint8Array(l));}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new LI(Hg.INVALID_PARAMS,n?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(EI.DATA_STREAM,{payload:QT(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-RB},!i);}sendMetadata(e){if(!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new LI(Hg.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(EI.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:QT(e)});}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(HC),!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"can not send custom report, not joined");await eI.sendCustomReportMessage(this._joinInfo.sid,e);}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats();}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats();}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats();}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats();}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats();}async pickSVCLayer(e,t){qg(t.spatialLayer,"spatialLayer",[0,1,2,3]),qg(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t);}catch(e){throw jC.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e;}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:i}=e;if(Yg(t,"apRTM"),zg(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,jC.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i);}_reset(){if(jC.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=sC.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map(),this._remoteStreamTypeCacheMap=new Map(),this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach(e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach(e=>e._close()),e._dataChannels.length=0);}),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new pS("client-publish"),this._subscribeMutex=new pS("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0;}catch(e){}if(this._moderation)try{this.setImageModeration(!1);}catch(e){}}_startSession(e,t){var i;const n=e||rS();e?jC.debug("[".concat(this._clientId,"] new Session ").concat(n)):jC.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=e?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n;const s={lts:new Date().getTime(),mode:this.mode,stringUid:(null==t?void 0:t.stringUid)||(null===(i=this._joinInfo)||void 0===i?void 0:i.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1};t?eI.sessionInit(this._sessionId,DB({cname:t.channel,appid:t.appId},s)):this._joinInfo?eI.sessionInit(this._sessionId,DB({cname:this._joinInfo.cname,appid:this._joinInfo.appId},s)):this._gateway.joinInfo&&eI.sessionInit(this._sessionId,DB({cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId},s)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n);}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&RC("FORCE_TURN")&&!RC("TURN_ENABLE_TCP")&&!RC("TURN_ENABLE_UDP"))throw new LI(Hg.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");jC.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this._p2pChannel instanceof hV){const e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(vv.PUBLISH,e,!0);}catch(e){throw i.throw(e),e;}await i.next();}this._p2pChannel.reportPublishEvent(!0,null);}else {const n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0);}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw i.throw(e),e;}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[]);}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof Rw&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!t.muted&&t.enabled||(await this._p2pChannel.muteLocalTrack(t));}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===Hg.WS_ABORT)return;throw t;}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new LI(Hg.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new LI(Hg.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));jC.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitratenew CV(this._joinInfo,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES),i=e=>{e.onLiveStreamError=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_ERROR,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_ERROR,e,t);},e.onLiveStreamWarning=(e,t)=>{eI.reportApiInvoke(this._sessionId,{name:hT.ON_LIVE_STREAM_WARNING,options:[e,t],tag:pT.TRACER}).onSuccess(),this.safeEmit(mT.LIVE_STREAMING_WARNING,e,t);},e.on(GI.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,"can not find join info to get worker manager"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i);});};switch(e){case RI.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case RI.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case RI.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(GI.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new LI(Hg.INVALID_OPERATION,"can not find join info to get worker manager"));mA(e,this._joinInfo,this._axiosCancelSource.token,ES).then(t).catch(i);}),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.safeEmit(mT.INJECT_STREAM_STATUS,e,t,i);}),this._injectStreamingClient;}}_createChannelMediaRelayClient(){if(!this._joinInfo){return new LI(Hg.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();}if(!this._channelMediaRelayClient){const{sendResolutionWidth:e,sendResolutionHeight:t}=this.getLocalVideoStats(),i={width:e,height:t};this._channelMediaRelayClient=new AV(this._joinInfo,this._clientId,this._config.websocketRetryConfig||ES,this._config.httpRetryConfig||ES,i),this._channelMediaRelayClient.on("state",e=>{e===qI.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.safeEmit(mT.CHANNEL_MEDIA_RELAY_STATE,e);}),this._channelMediaRelayClient.on("event",e=>{this.safeEmit(mT.CHANNEL_MEDIA_RELAY_EVENT,e);}),this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null===(i=this._channelMediaRelayClient)||void 0===i||i.setVideoProfile(t));};}return this._channelMediaRelayClient;}_handleUpdateDataChannel(e,t){const{added:i,deleted:n}=e,r=[];Array.isArray(i)&&i.length>0&&i.forEach(e=>{const{uid:i,stream_id:n,ordered:s,max_retrans_times:o,metadata:a}=e,c=this._users.find(e=>e._uintid===i);if(!c)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));jC.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),bn(r).call(r,c)||r.push(c),c._uintid||(c._uintid=i);if(!(-1!==c._dataChannels.findIndex(t=>t.id===e.stream_id))){const e={id:n,ordered:!!s,maxRetransmits:o,metadata:a},i=new oP(e);c._dataChannels.push(i),jC.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(mT.USER_PUBLISHED,c,"datachannel",e);}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(jC.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch(e=>{jC.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString());}));}),t&&(this.safeEmit(mT.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach(e=>{const{uid:t,stream_id:i}=e,n=this._users.find(e=>e._uintid===t);if(!n)return void jC.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const r=n._dataChannels.find(t=>t.id===e.stream_id);r&&(jC.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(n,[r]).then(e=>{if(n._dataChannels=n._dataChannels.filter(e=>e!==r),e)return this._gateway.unsubscribeDataChannel(e,n.uid);}),jC.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(r.id)),this.safeEmit(mT.USER_UNPUBLISHED,n,"datachannel",r._config));});}_handleRemoveDataChannels(e){const t=this._users.find(t=>t.uid===e.uid);if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){jC.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const i=()=>{jC.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach(e=>{this.safeEmit(mT.USER_UNPUBLISHED,t,"datachannel",e._config);});};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then(e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid);}),i();}}else jC.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"));}_handleGatewayEvents(){this._gateway.on(XI.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect();}),this._gateway.on(XI.CONNECTION_STATE_CHANGE,(e,t,i)=>{var n;if(i===ET.FALLBACK)return;const r=()=>{this.safeEmit(mT.CONNECTION_STATE_CHANGE,e,t,i);};if(eI.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:hT.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:pT.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),jC.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach(e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0);}),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var s;this._streamFallbackTypeCacheMap.forEach((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e);});}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{jC.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e);});}),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(s=this._joinInfo)||void 0===s?void 0:s.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{jC.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"));}).catch(e=>{jC.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e));}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter(e=>!e._trust_in_room_).forEach(e=>{jC.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid});});},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach(e=>{e._trust_audio_mute_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,av.AUDIO,!1)),e._trust_video_mute_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,av.VIDEO,!1)),e._trust_audio_enabled_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(jC.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(jC.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}));}));},1e3));}r();}),this._gateway.on(XI.REQUEST_NEW_GATEWAY_LIST,(e,t)=>{if(!this._joinInfo)return t(new LI(Hg.UNEXPECTED_ERROR,"can not recover, no join info"));uA(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ES,this.store).then(t=>{this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);const i=[];t.gatewayInfo.gatewayAddrs.forEach(e=>{let{address:t}=e;const[n,r]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:n,port:r}):i.push({host:n,port:r});}),e(i);}).catch(t);}),this._gateway.on(XI.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(mT.NETWORK_QUALITY,e);}),this._gateway.on(XI.STREAM_TYPE_CHANGE,(e,t)=>{this.safeEmit(mT.STREAM_TYPE_CHANGED,e,t);eI.reportApiInvoke(this._sessionId,{name:hT.STREAM_TYPE_CHANGE,options:[e,t],tag:pT.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}));}),this._gateway.on(XI.IS_P2P_DISCONNECTED,e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0);}),this._gateway.on(XI.NEED_RENEW_SESSION,()=>{this._startSession();}),this._gateway.on(XI.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e));}catch(e){i(e);}}),this._gateway.on(XI.JOIN_RESPONSE,(e,t)=>{if(this.store.useP2P)return;const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:s,setup:o,cname:a}=Rx(e.ortc,t);this._p2pChannel.connect(n,i,r,s,o,a);}),this._gateway.on(XI.REQUEST_DC_CONNECTION_PARAMS,e=>{e(this._p2pChannel.getEstablishParams());}),this._gateway.on(XI.RESET_SIGNAL,e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents();}),this._gateway.on(XI.DATACHANNEL_FAILBACK,()=>{this._joinGateway();}),this._gateway.on(XI.DATACHANNEL_PRECONNECT,async(e,t,i,n)=>{var r,s,o,a,c,d;await this._p2pChannel.startP2PConnection({turnServer:null===(r=this._joinInfo)||void 0===r?void 0:r.turnServer},!0);const l=function(e,t){let i;return t&&t.ip&&"number"==typeof t.port?(i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],jC.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(i.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),jC.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],i;}(e,t);return this._p2pChannel.preConnect({iceUfrag:"".concat(null===(s=this._joinInfo)||void 0===s?void 0:s.apResponse.cid,"_").concat(null===(o=this._joinInfo)||void 0===o?void 0:o.apResponse.cert),icePwd:"".concat(null===(a=this._joinInfo)||void 0===a?void 0:a.apResponse.cid,"_").concat(null===(c=this._joinInfo)||void 0===c?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(d=RC("FINGERPRINT"))&&void 0!==d?d:e.fingerprint}]},l,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(i).catch(n);});}_handleGatewaySignalEvents(){this._gateway.signal.on(fI.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(fI.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(fI.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc)),this._gateway.signal.on(fI.ON_ADD_VIDEO_STREAM,e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId)),this._gateway.signal.on(fI.ON_REMOTE_DATASTREAM_UPDATE,e=>{this._handleUpdateDataChannel(e);}),this._gateway.signal.on(fI.ON_REMOTE_FULL_DATASTREAM_INFO,e=>{this._handleUpdateDataChannel({added:e.datastreams,deleted:[]},!0);}),this._gateway.signal.on(fI.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(fI.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(fI.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,av.AUDIO,!0)),this._gateway.signal.on(fI.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,av.AUDIO,!1)),this._gateway.signal.on(fI.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,av.VIDEO,!0)),this._gateway.signal.on(fI.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,av.VIDEO,!1)),this._gateway.signal.on(fI.RECEIVE_METADATA,e=>{const t=XT(e.metadata);this.safeEmit(mT.RECEIVE_METADATA,e.uid,t);}),this._gateway.signal.on(fI.ON_DATA_STREAM,async e=>{var t;if(!e)return;let i=XT(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&bn(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.lengtht.uid===e.uid),r=null==t?void 0:t.audioRecv.find(e=>e.ssrc===(null==i?void 0:i._audioSSRC));n=null==r?void 0:r.jitterBufferMs;}null==n&&(n=0),bB(DB(DB({},e),{},{payload:i}),n,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)});}),this._gateway.signal.on(fI.ON_CRYPT_ERROR,()=>{JT(()=>{jC.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(mT.CRYPT_ERROR);},this._sessionId);}),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(fI.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{jC.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,ET.TOKEN_EXPIRE),this.safeEmit(mT.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset();}),this._gateway.signal.on(fI.ON_STREAM_FALLBACK_UPDATE,e=>{jC.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(mT.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover");}),this._gateway.signal.on(fI.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),jC.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))));}),this._gateway.signal.on(fI.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0);}),this._gateway.signal.on(fI.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1);}),this._gateway.signal.on(_I.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case EI.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var i,n;const r=e.some(e=>{let{stream_type:t}=e;return t===JI.Audio;}),s=e.some(e=>{let{stream_type:t}=e;return t!==JI.Audio;}),o=e.some(e=>{let{stream_type:t}=e;return t===JI.Screen||t===JI.ScreenLow;});"offer"===t.state&&eI.publish(this._joinInfo.sid,{eventElapse:RU.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:Hg.TIMEOUT,audio:r,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:o,audioName:r?null===(i=e.find(e=>{let{stream_type:t}=e;return t===JI.Audio;}))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0,videoName:s?null===(n=e.find(e=>{let{stream_type:t}=e;return t!==JI.Audio;}))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0});}break;}case EI.SUBSCRIBE:t&&eI.subscribe(this._joinInfo.sid,{succ:!1,ec:Hg.TIMEOUT,audio:t.stream_type===av.AUDIO,video:t.stream_type===av.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:RU.measureFromSubscribeStart(this.store.clientId,t.ssrcId)});}}),this._gateway.signal.on(fI.ON_P2P_OK,e=>{this.uid,this._uid;}),this._gateway.signal.on(fI.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;RC("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter(e=>!sI(e.string_id||e.stream_id,this.channelName)));const t=[],i=[];for(const n of e.users){let e=this._users.find(e=>e._uintid===n.stream_id);e?e._trust_in_room_=!0:(e=new sV(n.string_id||n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(mT.USER_JOINED,e)));const r=ZI.Audio&n.stream_type,s=(ZI.Video|ZI.LwoVideo)&n.stream_type,o=0!=(65280&n.stream_type),a=r&&e.hasAudio,c=s&&e.hasVideo;s&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc,e._rtxSsrcId=n.video_rtx),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!a&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(mT.USER_PUBLISHED,e,"audio")),s&&!c&&0===this.getListeners(mT.PUBLISHED_USER_LIST).length&&(jC.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(mT.USER_PUBLISHED,e,"video")),(r&&!a||s&&!c||o)&&t.push(e),s&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"});}i.length>0&&(jC.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map(e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType)).join("; ")," ")),this.massSubscribe(i).catch(e=>{jC.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString());})),this.getListeners(mT.PUBLISHED_USER_LIST).length>0?RC("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(jC.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>e.uid).join(", "))),this.safeEmit(mT.PUBLISHED_USER_LIST,t)):jC.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map(e=>e.uid).join(", ")));}),this._gateway.signal.on(fI.ON_RTP_CAPABILITY_CHANGE,e=>{const{video_codec:t}=e;this._p2pChannel instanceof cF&&this._p2pChannel.updateRemoteRTPCapabilities(t.map(e=>e.toLowerCase()).filter(e=>{var t;return bn(t=Object.keys(bC)).call(t,e);}));});}_handleP2PEvents(){this._gateway.signal.on(fI.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect();}),this._gateway.signal.on(vv.PUBLISH,(e,t,i)=>{const{uid:n}=e;e.forEach(e=>{const{kind:r,ssrcs:s,mid:o,isMuted:a}=e;this._handleP2PAddAudioOrVideoStream(r,n,s[0].ssrcId,o);const c=this._users.find(e=>e.uid===n);return c&&this._p2pChannel instanceof hV?this._p2pChannel.mockSubscribe(c,r,s[0].ssrcId,o).then(()=>{t();}).catch(i):t(),this._handleMuteStream(n,r,!!a);});}),this._gateway.signal.on(vv.CALL,async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{var n;t(await this._p2pChannel.startP2P({turnServer:null===(n=this._joinInfo)||void 0===n?void 0:n.turnServer},e));}catch(e){i(e);}}),this._gateway.signal.on(_I.P2P_CONNECTION,async e=>{this._p2pChannel instanceof hV&&(await this._p2pChannel.p2pConnect(e));}),this._gateway.signal.on(vv.UNPUBLISH,async(e,t,i)=>{if(this._p2pChannel instanceof hV){const{unpubMsg:n,uid:r}=e,s=this._users.find(e=>e.uid===r);if(!s)return jC.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{n.forEach(async e=>{let{stream_type:t}=e;const i=t===JI.Audio?av.AUDIO:av.VIDEO;await this._p2pChannel.unsubscribe(s,i),this._handleMuteStream(r,i,!0);}),t();}catch(e){i(e);}}}),this._gateway.signal.on(vv.CONTROL,async(e,t)=>{const{action:i}=e;switch(i){case Av.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,av.VIDEO,!0);break;case Av.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,av.AUDIO,!0);break;case Av.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,av.VIDEO,!1);break;case Av.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,av.AUDIO,!1);}}),this._gateway.signal.on(vv.RESTART_ICE,async(e,t,i)=>{if(this._p2pChannel instanceof hV)try{const{direction:i,iceParameter:n}=e;if(i!==TI.SEND_ONLY||n){t(await this._p2pChannel.restartICE(i,n));}else this._p2pChannel.handleDisconnect(i),t();}catch(e){i(e);}}),this._gateway.signal.on(vv.CANDIDATE,e=>{if(this._p2pChannel instanceof hV){const{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i);}}),this._p2pChannel.on(hv.RequestP2PRestartICE,async(e,t,i)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(vv.RESTART_ICE,e,i===TI.SEND_ONLY));}catch(e){i(e);}}),this._p2pChannel.on(hv.LocalCandidate,e=>{this._gateway.sendExtensionMessage(vv.CANDIDATE,JSON.stringify(e),!0);}),this._p2pChannel.on(hv.RequestP2PMuteLocal,async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(vv.CONTROL,e,!0),t();}catch(e){i(e);}}),this._p2pChannel.on(hv.RequestP2PUnmuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestP2PMuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.StateChange,(e,t)=>{t===uv.Connected&&this._p2pChannel.republish();});}_handleP2PChannelEvents(){this._p2pChannel.on(hv.RequestMuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestUnmuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t();}catch(e){e.code===Hg.DISCONNECT_P2P?t():i(e);}else t();}),this._p2pChannel.on(hv.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i);}),this._p2pChannel.on(hv.RequestRePublishDataChannel,(e,t,i)=>{cg.all(e.map(async e=>{await this._p2pChannel.publishDataChannel([e]);const t={streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId};try{await this._gateway.publishDataChannel(this._uid,t,!0);}catch(e){if(e.code!==Hg.DISCONNECT_P2P)throw e;}})).then(t).catch(i);}),this._p2pChannel.on(hv.RequestReSubscribe,async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===av.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t();}catch(e){i(e);}}),this._p2pChannel.on(hv.RequestUpload,(e,t)=>{this._gateway.upload(e,t);}),this._p2pChannel.on(hv.RequestUploadStats,e=>{this._gateway.uploadWRTCStats(e);}),this._p2pChannel.on(hv.MediaReconnectStart,e=>{this.safeEmit(mT.MEDIA_RECONNECT_START,e);}),this._p2pChannel.on(hv.MediaReconnectEnd,e=>{this.safeEmit(mT.MEDIA_RECONNECT_END,e);}),this._p2pChannel.on(hv.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT());}),this._p2pChannel.on(hv.RequestRestartICE,async e=>{if(this._p2pChannel instanceof hV)return;const t=await this._p2pChannel.restartICE(e),i=await t.next();if(i.done)return;const n=i.value;let r;try{r=await this._gateway.restartICE({iceParameters:n});}catch(e){return void t.throw(e);}const{iceParameters:s}=function(e){const t=e.iceParameters;return {iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}};}(r);await t.next({remoteIceParameters:s});}),this._p2pChannel.on(hv.RequestReconnect,async()=>{this._gateway.reconnect();}),this._p2pChannel.on(hv.RequestReconnectPC,async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:s}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),{dtlsParameters:o,iceParameters:a,candidates:c,rtpCapabilities:d,setup:l,cname:u}=Rx(r,s);await this._p2pChannel.connect(a,o,c,d,l,u),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe();}),this._p2pChannel.on(hv.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i();}),this._p2pChannel.on(hv.P2PLost,()=>{this.safeEmit(mT.P2P_LOST,this.store.uid);}),this._p2pChannel.on(hv.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig);}),this._p2pChannel.on(hv.ConnectionTypeChange,e=>{this.safeEmit(mT.IS_USING_CLOUD_PROXY,e);}),this._p2pChannel.on(hv.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50});}),this._p2pChannel.on(hv.QueryClientConnectionState,e=>{e(this.connectionState);});}getKeyMetrics(){return this.store.keyMetrics;}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{const t=[...new Set(e.inspectType)];t.forEach(e=>{var t;if(!bn(t=["supervise","moderation"]).call(t,e))throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] ").concat(e," is not a valid inspect type."));}),e.inspectType=t;}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const t=new FF(e);this._inspect=t,this.handleVideoInspectEvents(this._inspect),await t.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES);}catch(e){throw Array.isArray(e)?e[0]:e;}}async disableContentInspect(){if(!this._inspect)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0;}catch(e){throw Array.isArray(e)?e[0]:e;}}async setImageModeration(e,t){if(Yg(e,"enabled"),e){if(!t)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config is necessary"));if(zg(t.interval,"interval",1e3,1/0),t&&t.extraInfo&&t.extraInfo.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config.extraInfo length cannot exceed 1024 bytes"));if(t&&t.vendor&&t.vendor.length>1024)throw new LI(Hg.INVALID_PARAMS,"[".concat(this._clientId,"] config.vendor length cannot exceed 1024 bytes"));if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,'] can not enable image moderation, not joined"'));try{if(this._moderation)return void this._moderation.updateConfig(t);const e=new gB(t);this._moderation=e,this.handleImageModerationEvents(this._moderation),await e.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},ES);}catch(e){throw Array.isArray(e)?e[0]:e;}}else {if(!this._moderation)throw new LI(Hg.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0;}catch(e){throw Array.isArray(e)?e[0]:e;}}}setP2PTransport(e){if(function(e){qg(e,"transport",["default","auto","relay","sd-rtn"]);}(e),"p2p"!==this.mode)throw new LI(Hg.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,jC.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e));}handleImageModerationEvents(e){e.on(Cv.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(mT.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===Rv.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new LI(Hg.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage();}}),e.on(Cv.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0]);});}handleVideoInspectEvents(e){e.on(mv.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(mT.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===_v.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(mT.CONTENT_INSPECT_ERROR,new LI(Hg.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage();}}),e.on(mv.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===Hg.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return jC.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.safeEmit(mT.CONTENT_INSPECT_RESULT,e,t);}),e.on(mv.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0]);});}getJoinChannelServiceRecords(){return jC.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords;}async setPublishAudioFilterEnabled(e){Yg(e,"enabled"),SC("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&(await this._gateway.setPublishAudioFilterEnabled(e));}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0;}}}DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"leave",null),DI([$C({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof lb))return [t];t=[t];}return t.map(e=>e?Object(e).toString():"null");}}),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",cg)],PB.prototype,"publish",null),DI([$C({argsMap:(e,t)=>(t||(t=[]),t instanceof aP?[t.getChannelId()]:(Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId())))}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"unpublish",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],PB.prototype,"subscribe",null),DI([$C({argsMap:(e,t,i)=>[t,i]}),PI("design:type",Function),PI("design:paramtypes",[Object,String]),PI("design:returntype",cg)],PB.prototype,"presubscribe",null),DI([$C({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return [null==t?void 0:t.uid,i];})}),PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],PB.prototype,"massSubscribe",null),DI([$C({argsMap:(e,t,i,n)=>[t.uid,i,n]}),PI("design:type",Function),PI("design:paramtypes",[sV,String,Number]),PI("design:returntype",cg)],PB.prototype,"unsubscribe",null),DI([$C({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return {uid:null==t?void 0:t.uid,mediaType:i};})}),PI("design:type",Function),PI("design:paramtypes",[Array]),PI("design:returntype",cg)],PB.prototype,"massUnsubscribe",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setLowStreamParameter",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"enableDualStream",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"disableDualStream",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Object]),PI("design:returntype",cg)],PB.prototype,"setClientRole",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setTurnServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",void 0)],PB.prototype,"setLicense",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",void 0)],PB.prototype,"startProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],PB.prototype,"stopProxyServer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",void 0)],PB.prototype,"setLocalAccessPointsV2",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Array,String]),PI("design:returntype",void 0)],PB.prototype,"setLocalAccessPoints",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Number]),PI("design:returntype",cg)],PB.prototype,"setRemoteDefaultVideoStreamType",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",cg)],PB.prototype,"setRemoteVideoStreamType",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Number]),PI("design:returntype",cg)],PB.prototype,"setStreamFallbackOption",null),DI([$C({argsMap:(e,t)=>[t]}),PI("design:type",Function),PI("design:paramtypes",[String,String,Uint8Array,Boolean]),PI("design:returntype",void 0)],PB.prototype,"setEncryptionConfig",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],PB.prototype,"renewToken",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",void 0)],PB.prototype,"enableAudioVolumeIndicator",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Boolean]),PI("design:returntype",cg)],PB.prototype,"startLiveStreaming",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setLiveTranscoding",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",cg)],PB.prototype,"stopLiveStreaming",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String,Object]),PI("design:returntype",cg)],PB.prototype,"addInjectStreamUrl",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"removeInjectStreamUrl",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[IV]),PI("design:returntype",cg)],PB.prototype,"startChannelMediaRelay",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[IV]),PI("design:returntype",cg)],PB.prototype,"updateChannelMediaRelay",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"stopChannelMediaRelay",null),DI([$C({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"sendCustomReportMessage",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object,Object]),PI("design:returntype",cg)],PB.prototype,"pickSVCLayer",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"setRTMConfig",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Object]),PI("design:returntype",cg)],PB.prototype,"enableContentInspect",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",cg)],PB.prototype,"disableContentInspect",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Boolean,Object]),PI("design:returntype",cg)],PB.prototype,"setImageModeration",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[String]),PI("design:returntype",void 0)],PB.prototype,"setP2PTransport",null),DI([$C({reportResult:!0}),PI("design:type",Function),PI("design:paramtypes",[]),PI("design:returntype",Array)],PB.prototype,"getJoinChannelServiceRecords",null),DI([$C(),PI("design:type",Function),PI("design:paramtypes",[Boolean]),PI("design:returntype",cg)],PB.prototype,"setPublishAudioFilterEnabled",null);class LB{constructor(e,t){sh(this,"id",0),sh(this,"element",void 0),sh(this,"peerPair",void 0),sh(this,"context",void 0),sh(this,"audioPlayerElement",void 0),sh(this,"audioTrack",void 0),LB.count+=1,this.id=LB.count,this.element=e,this.context=t;}initPeers(){this.peerPair=[new RTCPeerConnection(),new RTCPeerConnection()],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t;};}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new cg(t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription);};});},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n);}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print();}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t);}catch(e){throw new LI(Hg.LOCAL_AEC_ERROR,e.toString()).print();}if(!t){throw new LI(Hg.LOCAL_AEC_ERROR,"no dest node when local aec").print();}const i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i;}getElement(){return this.element;}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp();}close(){jC.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach(e=>{e.close();}),this.peerPair=void 0,this.audioPlayerElement=void 0;}}sh(LB,"count",0);const kB=window.AudioContext||window.webkitAudioContext;class MB{constructor(){sh(this,"units",[]),sh(this,"context",void 0);}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return jC.debug("the system does not need to process local aec"),-1;this.context||(this.context=new kB());let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new LB(e,this.context),this.units.push(t)),t.startEchoCancellation(),jC.debug("start processing local audio echo cancellation, id is",t.id),t.id;}_doesEnvironmentNeedAEC(){return Sg().name!==Eg.SAFARI;}}DI([$C({report:eI}),PI("design:type",Function),PI("design:paramtypes",[HTMLAudioElement]),PI("design:returntype",Number)],MB.prototype,"processExternalMediaAEC",null);const UB=new MB();function xB(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable;})),i.push.apply(i,n);}return i;}function VB(e){for(var t=1;t1&&void 0!==arguments[1]&&arguments[1];if(!FB)return;const i=GB._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);const n=e=>{if(!(e&&e.blockedURI&&(GB.onSecurityPolicyViolation||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;RC("CSP_DETECTED_HOSTNAME_LIST").some(e=>bn(t).call(t,e))&&(GB.onSecurityPolicyViolation&&"function"==typeof GB.onSecurityPolicyViolation&&GB.onSecurityPolicyViolation(e),GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0&&GB.safeEmit(Tv.SECURITY_POLICY_VIOLATION,e));};i&&FB.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||GB.getListeners(Tv.SECURITY_POLICY_VIOLATION).length>0)&&FB.addEventListener("securitypolicyviolation",n),GB._cspEventHandlerPointer=n;}SC("PROCESS_ID","process-".concat(nS(8,""),"-").concat(nS(4,""),"-").concat(nS(4,""),"-").concat(nS(4,""),"-").concat(nS(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter");}catch(e){return void jC.error("Error loading sdk config",e.message);}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();jC.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e=>{if(Object.prototype.hasOwnProperty.call(TC,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;CC[e]=n,TC[e]=n;}});}catch(t){jC.error("Error loading mutableParamsCache: ".concat(e),t.message);}}(),Array.isArray(CC.AREAS)&&CC.AREAS.length>0&&Jy(CC.AREAS,!0);const jB=(e,t,i)=>{jC.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),SC(e,t,i);},GB=function(e){const t=new dT(),i=e,n={getListeners:t.getListeners.bind(t),on:(e,i)=>(function(e,t){e===Tv.SECURITY_POLICY_VIOLATION&&BB(t,!0);}(e,i),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return VB(VB({},i),n);}({__TRACK_LIST__:VA,VERSION:EC,BUILD:gC,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:jB,getParameter:RC,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection();t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const i=(await t.createOffer()).sdp;if(!i)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t;}(i);}catch(e){throw new LI(Hg.CREATE_OFFER_FAILED,e.toString&&e.toString()).print();}return e;},checkSystemRequirements:function(){const e=eI.reportApiInvoke(null,{name:hT.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:pT.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n);}catch(e){return jC.error("check system requirement failed: ",e),!1;}let i=!1;const n=Sg();n.name===Eg.CHROME&&Number(n.version)>=58&&(!yg()||vg())&&(i=!0),n.name===Eg.FIREFOX&&Number(n.version)>=56&&(i=!0),n.name===Eg.OPERA&&Number(n.version)>=45&&(i=!0),n.name===Eg.SAFARI&&Number(n.version)>=11&&(i=!0),(Fg()||Sg().name===Eg.QQ)&&(i=!0),jC.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r;},getDevices:function(e){return kb.enumerateDevices(!0,!0,e);},getMicrophones:function(e){return kb.getRecordingDevices(e);},getCameras:function(e){return kb.getCamerasDevices(e);},getElectronScreenSources:yb,getPlaybackDevices:function(e){return kb.getSpeakers(e);},createClient:function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=eI.reportApiInvoke(null,{name:hT.CREATE_CLIENT,options:[t],tag:pT.TRACER});try{!function(e){qg(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),qg(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&qg(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Xg(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&CT(e.turnServer),void 0!==e.httpRetryConfig&&ST(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&ST(e.websocketRetryConfig);}(t);}catch(e){throw i.onError(e),e;}return OB()||("vp9"===t.codec&&(t.codec="vp8",jC.debug("browser not support vp9, force use vp8")),SC("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),i.onSuccess(),new PB(DB(DB({forceWaitGatewayResponse:!0},t),{},{role:bn(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}));},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CAM_VIDEO_TRACK,options:[vw({},e)]}),i=rw(e),n=nS(8,"track-cam-");let r=null;const s="720p_auto"===e.encoderConfig;jC.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{r=(await Nb({video:i},n)).getVideoTracks()[0]||null;}catch(e){throw t.onError(e),e;}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(jC);}e.optimizationMode&&yw(n,r,e,LA(e.encoderConfig));const o=new Cw(r,e,i,e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return s&&o.startMonitorStats(),t.onSuccess(o.getTrackId()),jC.info("create camera video success, trackId:",n),o;},createCustomVideoTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new Rw(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,nS(8,"track-cus-"),[jA.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),jC.info("create custom video track success with config",e,"trackId",i.getTrackId()),i;},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_SCREEN_VIDEO_TRACK,options:[vw({},e),t]}),n="720p_auto"===e.encoderConfig;e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const r=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Ag()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:s}=e;(Ng(107)||Dg(107)||Pg(93))&&(i&&(qg(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(qg(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(qg(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(Ng(105)||Dg(105)||Pg(91))&&s&&(qg(s,"systemAudio",["exclude","include"]),t.systemAudio=s),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const o=e.encoderConfig?kA(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:o?o.width:void 0,maxHeight:o?o.height:void 0},o&&(o.frameRate&&("number"==typeof o.frameRate?(t.mandatory.maxFrameRate=o.frameRate,t.mandatory.minFrameRate=o.frameRate):(t.mandatory.maxFrameRate=o.frameRate.max||o.frameRate.ideal||o.frameRate.exact||void 0,t.mandatory.minFrameRate=o.frameRate.min||o.frameRate.ideal||o.frameRate.exact||void 0),t.frameRate=o.frameRate),o.width&&(t.width=o.width),o.height&&(t.height=o.height)),t;}(e),s=nS(8,"track-scr-v-");let o=null,a=null;const c=IA();if(!c.supportShareAudio&&"enable"===t){const e=new Kg(Hg.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw(jC);}jC.info("start create screen video track with config",e,"withAudio",t,"trackId",s);try{const e=await Nb({screen:r,screenAudio:"auto"===t?c.supportShareAudio:"enable"===t},s);o=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null;}catch(e){throw i.onError(e),e;}if(!o){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(jC);}if(!a&&"enable"===t){o&&o.stop();const e=new Kg(Hg.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw(jC);}if(e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode){yw(s,o,e,e.encoderConfig&&kA(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax);}const d=new Rw(o,e.encoderConfig?kA(e.encoderConfig):{},e.scalabiltyMode?MA(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,s,[jA.SCREEN_TRACK]);if(n&&d.startMonitorStats(),!a)return i.onSuccess(d.getTrackId()),jC.info("create screen video track success","video:",d.getTrackId()),d;const l=new ew(a,void 0,nS(8,"track-scr-a-"),!1);return i.onSuccess([d.getTrackId(),l.getTrackId()]),jC.info("create screen video track success","video:",d.getTrackId(),"audio:",l.getTrackId()),[d,l];},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n="720p_auto"===t.encoderConfig,r=rw(t),s=sw(e),o=nS(8,"track-mic-"),a=nS(8,"track-cam-");let c=null,d=null;jC.info("start create camera video track(".concat(a,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await Nb({audio:s,video:r},"".concat(o,"-").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0];}catch(e){throw i.onError(e),e;}if(!c||!d){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw(jC);}t.optimizationMode&&yw(a,d,t,LA(t.encoderConfig));const l=new tw(c,e,s,o),u=new Cw(d,t,r,t.scalabiltyMode?MA(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,a);return n&&u.startMonitorStats(),i.onSuccess([l.getTrackId(),u.getTrackId()]),jC.info("create camera video track(".concat(a,") and microphone audio track(").concat(o,") success")),[l,u];},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=sw(e),n=nS(8,"track-mic-");let r=null;jC.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await Nb({audio:i},n)).getAudioTracks()[0]||null;}catch(e){throw t.onError(e),e;}if(!r){const e=new Kg(Hg.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw(jC);}const s=new tw(r,e,i,n);return t.onSuccess(s.getTrackId()),jC.info("create microphone audio track success, trackId:",n),s;},createCustomAudioTrack:function(e){const t=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new ew(e.mediaStreamTrack,e.encoderConfig?xA(e.encoderConfig):{},nS(8,"track-cus-"),!1);return jC.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i;},createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:i,encoderConfig:n}=e;let{source:r}=e;const s={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:i,encoderConfig:n},o=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CREATE_BUFFER_AUDIO_TRACK,options:[s]});if(RC("DISABLE_WEBAUDIO"))throw new Kg(Hg.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const a=nS(8,"track-buf-");jC.info("start create buffer source audio track with config",JSON.stringify(s),"trackId",a);const c=r;if(!(r instanceof AudioBuffer))try{r=await cw(r,i);}catch(e){return o.onError(e),e.throw(jC);}const d=new ow(r),l=new iw(c,d,n?xA(n):{},a);return jC.info("create buffer source audio track success, trackId:",a),o.onSuccess(l.getTrackId()),l;},setAppType:function(e){if(jC.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw jC.debug("Invalid appType"),new LI(Hg.INVALID_PARAMS,"invalid app type",e);SC("APP_TYPE",Math.floor(e));},setLogLevel:function(e){jC.setLogLevel(e);},enableLogUpload:function(){RC("USE_NEW_LOG")?SC("UPLOAD_LOG",!0):jC.enableLogUpload();},disableLogUpload:function(){RC("USE_NEW_LOG")?SC("UPLOAD_LOG",!1):jC.disableLogUpload();},createChannelMediaRelayConfiguration:function(){return new IV();},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof ew||e instanceof Nw)){const e=new LI(Hg.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw();}t&&t<1e3&&(t=1e3);const n=e instanceof ew?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let s=r,o=r;const a=Date.now();return new cg(r=>{const c=setInterval(()=>{const d=e.getVolumeLevel();s=d>s?d:s,o=d1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,o={duration:u,deviceLabel:n,maxVolumeLevel:s,result:t};jC.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(o))),i.onSuccess(o),r(t);}},200);});},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=eI.reportApiInvoke(null,{tag:pT.TRACER,name:hT.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof Rw||e instanceof Ow)){const e=new LI(Hg.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw();}t&&t<1e3&&(t=1e3);const n=e instanceof Rw?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(bg()||Ig())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([r]),s.play();const o=document.createElement("canvas");o.width=160,o.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,i,n){let r,s=0,o=null;return new cg((a,c)=>{function d(){s>n&&r&&(r(),a(s));const t=i.getContext("2d");if(!t){const e=new LI(Hg.UNEXPECTED_ERROR,"can not get canvas 2d context.");return jC.error(e.toString()),void c(e);}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),l=Math.floor(d.data.length/3);if(o){for(let e=0;e{r&&(r(),a(s));},t),r=Tb(()=>{d();},30);});}(s,t,o,4),c=Date.now()-e;}catch(e){throw i.onError(e),e;}wB===Eg.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:n,result:d};return jC.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),d;},setArea:Jy,audioElementPlayCenter:Gb,resumeAudioContext:function(){Gb.autoResumeAfterInterruption(!0);},processExternalMediaAEC:function(e){UB.processExternalMediaAEC(e);},registerExtensions:function(e){const t=RC("PLUGIN_INFO")||[];e.forEach(e=>{"name"in e&&!bn(t).call(t,e.name)&&t.push(e.name);const i=e;i.__registered__=!0,i.logger.hookLog=jC.extLog,i.reporter.hookApiInvoke=eI.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach(e=>{i.parameters[e]=RC(e);});}),jB("PLUGIN_INFO",t);},ChannelMediaRelayError:zI,ChannelMediaRelayEvent:YI,ChannelMediaRelayState:qI,RemoteStreamFallbackType:HA,RemoteStreamType:WA,ConnectionDisconnectedReason:ET,AudienceLatencyLevelType:_T,AREAS:ev});return Object.defineProperties(GB,{onAudioAutoplayFailed:{get:()=>Ub.onAudioAutoplayFailed,set:e=>{Ub.onAudioAutoplayFailed=e;}},onAutoplayFailed:{get:()=>Ub.onAutoplayFailed,set:e=>{Ub.onAutoplayFailed=e;}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>GB._onSecurityPolicyViolation,set(e){GB._onSecurityPolicyViolation=e,BB(e);}},__CLIENT_LIST__:{get:()=>RC("SHOW_GLOBAL_CLIENT_LIST")?rI:[]}}),kb.on(rb.CAMERA_DEVICE_CHANGED,e=>{jC.info("camera device changed",JSON.stringify(e)),GB.onCameraChanged&&GB.onCameraChanged(e),GB.safeEmit(Tv.CAMERA_CHANGED,e);}),kb.on(rb.RECORDING_DEVICE_CHANGED,e=>{jC.info("microphone device changed",JSON.stringify(e)),GB.onMicrophoneChanged&&GB.onMicrophoneChanged(e),GB.safeEmit(Tv.MICROPHONE_CHANGED,e);}),kb.on(rb.PLAYOUT_DEVICE_CHANGED,e=>{jC.debug("playout device changed",JSON.stringify(e)),GB.onPlaybackDeviceChanged&&GB.onPlaybackDeviceChanged(e),GB.safeEmit(Tv.PLAYBACK_DEVICE_CHANGED,e);}),Gb.onAutoplayFailed=()=>{jC.info("detect audio element autoplay failed"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed();},_b.on("autoplay-failed",()=>{jC.info("detect webaudio autoplay failed"),Ub.onAudioAutoplayFailed&&Ub.onAudioAutoplayFailed(),GB.safeEmit(Tv.AUTOPLAY_FAILED);}),_b.on(vA.STATE_CHANGE,(e,t)=>{jC.info("audio context state changed: ".concat(t," => ").concat(e)),GB.onAudioContextStateChanged&&GB.onAudioContextStateChanged(e,t),GB.safeEmit(Tv.AUDIO_CONTEXT_STATE_CHANGED,e,t);}),wT.on(TT.NETWORK_STATE_CHANGE,(e,t)=>{jC.info("[network-indicator] network state changed, ".concat(t," => ").concat(e));}),window&&(window.__ARTC__=GB),GB;});})(AgoraRTC_NProduction);var AgoraRTC_NProductionExports=AgoraRTC_NProduction.exports;var AgoraRTC = /*@__PURE__*/getDefaultExportFromCjs(AgoraRTC_NProductionExports); var Event$1 = /*#__PURE__*/function () { function Event() { _classCallCheck(this, Event); this._stores = Object.create(null); } //订阅事件 ctx事件执行的上下文对象 _createClass(Event, [{ key: "on", value: function on(event, handler, ctx) { if (typeof handler !== 'function') { throw new Error('listener must be a function'); } (this._stores[event] = this._stores[event] || []).push({ cb: handler, ctx: ctx }); return this; } //事件类型只订阅一个事件,调用后删除 }, { key: "once", value: function once(event, handler, ctx) { var that = this; function on() { that.off(event, on); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } handler.apply(this, args); } this.on(event, on, ctx); return that; } //发布事件 }, { key: "emit", value: function emit(event) { var store = this._stores[event]; if (store && store.length) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } for (var i = 0, len = store.length; i < len; i++) { var _store$i$ctx; store[i].cb.apply((_store$i$ctx = store[i].ctx) !== null && _store$i$ctx !== void 0 ? _store$i$ctx : null, args); } } } //取消订阅 }, { key: "off", value: function off(event, handler) { // all 取消所有的订阅事件 if (!arguments.length) { this._stores = {}; return; } // specific event var store = this._stores[event]; if (!store) return; // remove all handlers 取消当前事件类型对应的所有事件 if (arguments.length === 1) { delete store[event]; return; } // remove specific handler 取消特定事件 for (var i = 0, len = store.length; i < len; i++) { if (store[i].cb === handler) { store.splice(i, 1); break; } } return; } }, { key: "destroy", value: function destroy() { this._stores = Object.create(null); } }]); return Event; }(); var uuid = function uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); }; // 客户端唯一标记 function clientUuid() { var clientId = localStorage.getItem('__client'); if (clientId) { return clientId; } clientId = 'C_' + uuid(); localStorage.setItem('__client', clientId); return clientId; } function pick(obj, keys) { return keys.reduce(function (acc, key) { if (obj.hasOwnProperty(key)) { acc[key] = obj[key]; } return acc; }, {}); } function set(obj, path, value) { if (Object(obj) !== obj) return obj; if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []; path.slice(0, -1).reduce(function (a, c, i) { return Object(a[c]) === a[c] ? a[c] : a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {}; }, obj)[path[path.length - 1]] = value; return obj; } function isObject$1(item) { return item && _typeof(item) === 'object' && !Array.isArray(item); } function merge(target, source) { var output = Object.assign({}, target); if (isObject$1(target) && isObject$1(source)) { Object.keys(source).forEach(function (key) { if (isObject$1(source[key])) { if (!(key in target)) Object.assign(output, _defineProperty({}, key, source[key]));else output[key] = merge(target[key], source[key]); } else { Object.assign(output, _defineProperty({}, key, source[key])); } }); } return output; } function formatDate(timestamp) { if (!timestamp) { return '--'; } var date = new Date(timestamp); var year = date.getFullYear(); var month = String(date.getMonth() + 1).padStart(2, '0'); var day = String(date.getDate()).padStart(2, '0'); var hours = String(date.getHours()).padStart(2, '0'); var minutes = String(date.getMinutes()).padStart(2, '0'); var seconds = String(date.getSeconds()).padStart(2, '0'); var milliseconds = String(date.getMilliseconds()).padStart(3, '0'); return "".concat(year, "-").concat(month, "-").concat(day, " ").concat(hours, ":").concat(minutes, ":").concat(seconds, ".").concat(milliseconds); } function isSupport() { return 'getUserMedia' in navigator; } function isSupportProtocol() { var _window$location = window.location, protocol = _window$location.protocol, hostname = _window$location.hostname; if (protocol === 'https:' || protocol == 'file:') { return true; } else if (hostname === 'localhost' || hostname === '127.0.0.1') { return true; } return false; } var http = { get: function get(url, param) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); var query; if (param) { query = Object.keys(param).map(function (item) { return "".concat(item, "=").concat(param[item]); }).join('&'); } xhr.open('get', query ? "".concat(url, "?").concat(query) : url); xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign')); xhr.responseType = 'json'; xhr.send(); xhr.timeout = 15000; xhr.onload = function () { resolve(xhr.response); }; xhr.ontimeout = function () { reject({ code: '504', text: 'timeout' }); }; }); }, post: function post(url, params) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Uuid', sessionStorage.getItem('_duix_sessionId')); xhr.setRequestHeader('Request-Date', new Date().getTime()); xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign')); xhr.send(JSON.stringify(params)); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { if (xhr.responseText) { resolve(JSON.parse(xhr.responseText)); } else { resolve(); } } else { reject('Error: ' + xhr.status); } } }; }); }, stream: function stream(url, data) { var xhr = new XMLHttpRequest(); xhr.open('post', url); xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.setRequestHeader('Uuid', sessionStorage.getItem('_duix_sessionId')); xhr.setRequestHeader('Request-Date', new Date().getTime()); xhr.setRequestHeader('sig', sessionStorage.getItem('_duix_sign')); xhr.timeout = 15000; xhr.send(data); return new Promise(function (resolve, reject) { xhr.onload = function () { resolve(xhr.response); }; xhr.onerror = function (err) { console.warn(err); reject(); }; xhr.ontimeout = function () { console.warn('Request timed out'); reject('Request timed out'); }; }); } }; function commonjsRequire(path) { throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } var localforage$1 = {exports: {}}; /*! localForage -- Offline Storage, Improved Version 1.10.0 https://localforage.github.io/localForage (c) 2013-2017 Mozilla, Apache License 2.0 */ (function (module, exports) { (function (f) { { module.exports = f(); } })(function () { return function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof commonjsRequire == "function" && commonjsRequire; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f; } var l = n[o] = { exports: {} }; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e); }, l, l.exports, e, t, n, r); } return n[o].exports; } var i = typeof commonjsRequire == "function" && commonjsRequire; for (var o = 0; o < r.length; o++) s(r[o]); return s; }({ 1: [function (_dereq_, module, exports) { (function (global) { var Mutation = global.MutationObserver || global.WebKitMutationObserver; var scheduleDrain; { if (Mutation) { var called = 0; var observer = new Mutation(nextTick); var element = global.document.createTextNode(''); observer.observe(element, { characterData: true }); scheduleDrain = function () { element.data = called = ++called % 2; }; } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { var channel = new global.MessageChannel(); channel.port1.onmessage = nextTick; scheduleDrain = function () { channel.port2.postMessage(0); }; } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { scheduleDrain = function () { // Create a