var By = Object.defineProperty;
var Fy = (r, e, t) => e in r ? By(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
var y = (r, e, t) => Fy(r, typeof e != "symbol" ? e + "" : e, t);
function Oy(r, e) {
  for (var t = 0; t < e.length; t++) {
    const i = e[t];
    if (typeof i != "string" && !Array.isArray(i)) {
      for (const s in i)
        if (s !== "default" && !(s in r)) {
          const n = Object.getOwnPropertyDescriptor(i, s);
          n && Object.defineProperty(r, s, n.get ? n : {
            enumerable: !0,
            get: () => i[s]
          });
        }
    }
  }
  return Object.freeze(Object.defineProperty(r, Symbol.toStringTag, { value: "Module" }));
}
var le = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function Fr(r) {
  return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
}
function Ny(r) {
  if (r.__esModule) return r;
  var e = r.default;
  if (typeof e == "function") {
    var t = function i() {
      return this instanceof i ? Reflect.construct(e, arguments, this.constructor) : e.apply(this, arguments);
    };
    t.prototype = e.prototype;
  } else t = {};
  return Object.defineProperty(t, "__esModule", { value: !0 }), Object.keys(r).forEach(function(i) {
    var s = Object.getOwnPropertyDescriptor(r, i);
    Object.defineProperty(t, i, s.get ? s : {
      enumerable: !0,
      get: function() {
        return r[i];
      }
    });
  }), t;
}
var qc = { exports: {} }, _r = typeof Reflect == "object" ? Reflect : null, yh = _r && typeof _r.apply == "function" ? _r.apply : function(e, t, i) {
  return Function.prototype.apply.call(e, t, i);
}, da;
_r && typeof _r.ownKeys == "function" ? da = _r.ownKeys : Object.getOwnPropertySymbols ? da = function(e) {
  return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e));
} : da = function(e) {
  return Object.getOwnPropertyNames(e);
};
function Gy(r) {
  console && console.warn && console.warn(r);
}
var ym = Number.isNaN || function(e) {
  return e !== e;
};
function Be() {
  Be.init.call(this);
}
qc.exports = Be;
qc.exports.once = Hy;
Be.EventEmitter = Be;
Be.prototype._events = void 0;
Be.prototype._eventsCount = 0;
Be.prototype._maxListeners = void 0;
var xh = 10;
function po(r) {
  if (typeof r != "function")
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof r);
}
Object.defineProperty(Be, "defaultMaxListeners", {
  enumerable: !0,
  get: function() {
    return xh;
  },
  set: function(r) {
    if (typeof r != "number" || r < 0 || ym(r))
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + r + ".");
    xh = r;
  }
});
Be.init = function() {
  (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
};
Be.prototype.setMaxListeners = function(e) {
  if (typeof e != "number" || e < 0 || ym(e))
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e + ".");
  return this._maxListeners = e, this;
};
function xm(r) {
  return r._maxListeners === void 0 ? Be.defaultMaxListeners : r._maxListeners;
}
Be.prototype.getMaxListeners = function() {
  return xm(this);
};
Be.prototype.emit = function(e) {
  for (var t = [], i = 1; i < arguments.length; i++) t.push(arguments[i]);
  var s = e === "error", n = this._events;
  if (n !== void 0)
    s = s && n.error === void 0;
  else if (!s)
    return !1;
  if (s) {
    var a;
    if (t.length > 0 && (a = t[0]), a instanceof Error)
      throw a;
    var o = new Error("Unhandled error." + (a ? " (" + a.message + ")" : ""));
    throw o.context = a, o;
  }
  var c = n[e];
  if (c === void 0)
    return !1;
  if (typeof c == "function")
    yh(c, this, t);
  else
    for (var l = c.length, d = bm(c, l), i = 0; i < l; ++i)
      yh(d[i], this, t);
  return !0;
};
function vm(r, e, t, i) {
  var s, n, a;
  if (po(t), n = r._events, n === void 0 ? (n = r._events = /* @__PURE__ */ Object.create(null), r._eventsCount = 0) : (n.newListener !== void 0 && (r.emit(
    "newListener",
    e,
    t.listener ? t.listener : t
  ), n = r._events), a = n[e]), a === void 0)
    a = n[e] = t, ++r._eventsCount;
  else if (typeof a == "function" ? a = n[e] = i ? [t, a] : [a, t] : i ? a.unshift(t) : a.push(t), s = xm(r), s > 0 && a.length > s && !a.warned) {
    a.warned = !0;
    var o = new Error("Possible EventEmitter memory leak detected. " + a.length + " " + String(e) + " listeners added. Use emitter.setMaxListeners() to increase limit");
    o.name = "MaxListenersExceededWarning", o.emitter = r, o.type = e, o.count = a.length, Gy(o);
  }
  return r;
}
Be.prototype.addListener = function(e, t) {
  return vm(this, e, t, !1);
};
Be.prototype.on = Be.prototype.addListener;
Be.prototype.prependListener = function(e, t) {
  return vm(this, e, t, !0);
};
function Uy() {
  if (!this.fired)
    return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
}
function Em(r, e, t) {
  var i = { fired: !1, wrapFn: void 0, target: r, type: e, listener: t }, s = Uy.bind(i);
  return s.listener = t, i.wrapFn = s, s;
}
Be.prototype.once = function(e, t) {
  return po(t), this.on(e, Em(this, e, t)), this;
};
Be.prototype.prependOnceListener = function(e, t) {
  return po(t), this.prependListener(e, Em(this, e, t)), this;
};
Be.prototype.removeListener = function(e, t) {
  var i, s, n, a, o;
  if (po(t), s = this._events, s === void 0)
    return this;
  if (i = s[e], i === void 0)
    return this;
  if (i === t || i.listener === t)
    --this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : (delete s[e], s.removeListener && this.emit("removeListener", e, i.listener || t));
  else if (typeof i != "function") {
    for (n = -1, a = i.length - 1; a >= 0; a--)
      if (i[a] === t || i[a].listener === t) {
        o = i[a].listener, n = a;
        break;
      }
    if (n < 0)
      return this;
    n === 0 ? i.shift() : Vy(i, n), i.length === 1 && (s[e] = i[0]), s.removeListener !== void 0 && this.emit("removeListener", e, o || t);
  }
  return this;
};
Be.prototype.off = Be.prototype.removeListener;
Be.prototype.removeAllListeners = function(e) {
  var t, i, s;
  if (i = this._events, i === void 0)
    return this;
  if (i.removeListener === void 0)
    return arguments.length === 0 ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : i[e] !== void 0 && (--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : delete i[e]), this;
  if (arguments.length === 0) {
    var n = Object.keys(i), a;
    for (s = 0; s < n.length; ++s)
      a = n[s], a !== "removeListener" && this.removeAllListeners(a);
    return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
  }
  if (t = i[e], typeof t == "function")
    this.removeListener(e, t);
  else if (t !== void 0)
    for (s = t.length - 1; s >= 0; s--)
      this.removeListener(e, t[s]);
  return this;
};
function Sm(r, e, t) {
  var i = r._events;
  if (i === void 0)
    return [];
  var s = i[e];
  return s === void 0 ? [] : typeof s == "function" ? t ? [s.listener || s] : [s] : t ? Wy(s) : bm(s, s.length);
}
Be.prototype.listeners = function(e) {
  return Sm(this, e, !0);
};
Be.prototype.rawListeners = function(e) {
  return Sm(this, e, !1);
};
Be.listenerCount = function(r, e) {
  return typeof r.listenerCount == "function" ? r.listenerCount(e) : Tm.call(r, e);
};
Be.prototype.listenerCount = Tm;
function Tm(r) {
  var e = this._events;
  if (e !== void 0) {
    var t = e[r];
    if (typeof t == "function")
      return 1;
    if (t !== void 0)
      return t.length;
  }
  return 0;
}
Be.prototype.eventNames = function() {
  return this._eventsCount > 0 ? da(this._events) : [];
};
function bm(r, e) {
  for (var t = new Array(e), i = 0; i < e; ++i)
    t[i] = r[i];
  return t;
}
function Vy(r, e) {
  for (; e + 1 < r.length; e++)
    r[e] = r[e + 1];
  r.pop();
}
function Wy(r) {
  for (var e = new Array(r.length), t = 0; t < e.length; ++t)
    e[t] = r[t].listener || r[t];
  return e;
}
function Hy(r, e) {
  return new Promise(function(t, i) {
    function s(a) {
      r.removeListener(e, n), i(a);
    }
    function n() {
      typeof r.removeListener == "function" && r.removeListener("error", s), t([].slice.call(arguments));
    }
    Am(r, e, n, { once: !0 }), e !== "error" && Zy(r, s, { once: !0 });
  });
}
function Zy(r, e, t) {
  typeof r.on == "function" && Am(r, "error", e, t);
}
function Am(r, e, t, i) {
  if (typeof r.on == "function")
    i.once ? r.once(e, t) : r.on(e, t);
  else if (typeof r.addEventListener == "function")
    r.addEventListener(e, function s(n) {
      i.once && r.removeEventListener(e, s), t(n);
    });
  else
    throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof r);
}
var $y = qc.exports;
const ve = /* @__PURE__ */ Fr($y);
let ht = console;
const Bn = "][";
function Gr(r, e = 2e3) {
  return r.map((t) => {
    const i = Ky(t);
    return e > 0 && typeof i == "string" && i.length > e ? i.substring(0, e) + "..." : i;
  });
}
function Ky(r) {
  if (r == null) return r;
  const e = typeof r;
  if (e === "string" || e != "object") return r;
  try {
    return JSON.stringify(r);
  } catch {
    return r.toString() ?? r;
  }
}
let S = class Le {
  static setLogger(e) {
    Le.ENABLE_DATETIME = console === e, ht = e;
  }
  static traceTag(...e) {
    return e.filter((t) => t !== null || t !== void 0).join(Bn);
  }
  static getLogTag(e) {
    if (!e)
      e = Le.GLOBAL_TAG;
    else if (Le.FORCE_GLOBAL_TAG)
      if (e.includes(Bn)) {
        let t = e.split(Bn);
        t[0] = Le.GLOBAL_TAG, e = t.join(Bn);
      } else
        e = Le.GLOBAL_TAG;
    return e;
  }
  static getLogger() {
    return ht;
  }
  static formatDate() {
    if (!Le.ENABLE_DATETIME) return "";
    let e = /* @__PURE__ */ new Date();
    return `[${e.toLocaleString() + "." + (e.getTime() % 1e3).toString().padStart(3, "0")}]`;
  }
  static e(e, ...t) {
    if (!Le.ENABLE_ERROR)
      return;
    e = Le.getLogTag(e);
    let s = `${this.formatDate()}[${e}] > ${t[0]}`;
    if (Le.ENABLE_CALLBACK)
      return Le.emitter.emit("log", "error", s);
    const n = Gr(t.slice(1), 0);
    ht.error ? ht.error(s, ...n) : ht.warn ? ht.warn(s, ...n) : ht.log(s, ...n);
  }
  /**
   * 关键打印信息
   * @param {*} tag
   * @param {...any} msgs
   */
  static k(e, ...t) {
    e = Le.traceTag(e, "KeyMSG"), Le.w(e, ...t);
  }
  static i(e, ...t) {
    if (!Le.ENABLE_INFO)
      return;
    e = Le.getLogTag(e);
    let s = `%c${this.formatDate()}[${e}] > ${t[0]}`;
    const n = "color:blue";
    if (Le.ENABLE_CALLBACK)
      return Le.emitter.emit("log", "info", s, n);
    const a = Gr(t.slice(1));
    ht.info ? ht.info(s, n, ...a) : ht.log(s, n, ...a);
  }
  static w(e, ...t) {
    if (!Le.ENABLE_WARN)
      return;
    e = Le.getLogTag(e);
    let s = `${this.formatDate()}[${e}] > ${t[0]}`;
    if (Le.ENABLE_CALLBACK)
      return Le.emitter.emit("log", "warn", s);
    const n = Gr(t.slice(1), 0);
    ht.warn ? ht.warn(s, ...n) : ht.log(s, ...n);
  }
  static d(e, ...t) {
    if (!Le.ENABLE_DEBUG)
      return;
    e = Le.getLogTag(e);
    let s = `${this.formatDate()}[${e}] > ${t[0]}`;
    if (Le.ENABLE_CALLBACK)
      return Le.emitter.emit("log", "debug", s);
    const n = Gr(t.slice(1));
    ht.debug ? ht.debug(s, ...n) : ht.log(s, ...n);
  }
  static v(e, ...t) {
    if (!Le.ENABLE_VERBOSE)
      return;
    e = Le.getLogTag(e);
    let s = `${this.formatDate()}[${e}] > ${t[0]}`;
    if (Le.ENABLE_CALLBACK)
      return Le.emitter.emit("log", "verbose", s);
    const n = Gr(t.slice(1));
    ht.log(s, ...n);
  }
};
S.GLOBAL_TAG = "RTCXWebSDK";
S.FORCE_GLOBAL_TAG = !1;
S.ENABLE_ERROR = !0;
S.ENABLE_INFO = !0;
S.ENABLE_WARN = !0;
S.ENABLE_DEBUG = !1;
S.ENABLE_VERBOSE = !1;
S.ENABLE_CALLBACK = !1;
S.ENABLE_DATETIME = !0;
S.emitter = new ve();
S.emitter.setMaxListeners(100);
var rt = /* @__PURE__ */ ((r) => (r.PreConnect = "PreConnect", r.GetDevPicture = "GetDevPicture", r.StartPTZAction = "StartPTZAction", r.StopPTZAction = "StopPTZAction", r.PTZActionControl = "PTZActionControl", r.PTZReset = "PTZReset", r.GetPTZPosition = "GetPTZPosition", r.PTZMove = "PTZMove", r.PTZUnitedMove = "PTZUnitedMove", r.GetPTZUnitedPosition = "GetPTZUnitedPosition", r.StartVoiceIntercom = "StartVoiceIntercom", r.StopVoiceIntercom = "StopVoiceIntercom", r.QueryRecordTimeList = "QueryRecordTimeList", r.QueryEventTimeList = "QueryEventTimeList", r.QueryRecordList = "QueryRecordList", r.QueryMonthRecord = "QueryMonthRecord", r.FormatStorageMedium = "FormatStorageMedium", r.StartVodByTime = "StartVodByTime", r.StartVod = "StartVod", r.StopVod = "StopVod", r.VodCtrl = "VodCtrl", r.P2PSignalSdp = "P2PSignalSdp", r.P2PSignalCandidate = "P2PSignalCandidate", r.StartP2PStreaming = "StartP2PStreaming", r.Reboot = "Reboot", r.GetWiFiList = "GetWiFiList", r.WiFiSwitch = "WiFiSwitch", r.TriggerFileCapture = "TriggerFileCapture", r.PlaybackEnd = "PlaybackEnd", r.WakeupHeartbeat = "WakeupHeartbeat", r.StopCmsLivePreview = "StopCmsLivePreview", r.CreateDataChannel = "CreateDataChannel", r.DestroyDataChannel = "DestroyDataChannel", r.DataChannelStatus = "DataChannelStatus", r))(rt || {}), Ke = /* @__PURE__ */ ((r) => (r[r.NO_ACK = 0] = "NO_ACK", r[r.NEED_ACK = 1] = "NEED_ACK", r))(Ke || {}), ha = /* @__PURE__ */ ((r) => (r.PLAY = "play", r.Push = "push", r.RECORD = "record", r.DEV_PLAY = "devPlay", r))(ha || {}), Na = /* @__PURE__ */ ((r) => (r.RTC = "rtc", r.RTMP = "rtmp", r.RTSP = "rtsp", r.HLS = "hls", r.FLV = "flv", r))(Na || {}), Ga = /* @__PURE__ */ ((r) => (r.RTC = "2", r.RTMP = "0", r.RTSP = "1", r.HLS = "99", r))(Ga || {}), hi = /* @__PURE__ */ ((r) => (r[r.LOCAL = 0] = "LOCAL", r[r.TEST = 1] = "TEST", r[r.PROD = 2] = "PROD", r))(hi || {}), ed = /* @__PURE__ */ ((r) => (r.zh_CN = "zh_CN", r.en_US = "en_US", r.fr_FR = "fr_FR", r.de_DE = "de_DE", r.ja_JP = "ja_JP", r.ko_KR = "ko_KR", r.es_ES = "es_ES", r.ru_RU = "ru_RU", r.it_IT = "it_IT", r))(ed || {}), vs = /* @__PURE__ */ ((r) => (r[r.REGION_CHINA_ONLY = 0] = "REGION_CHINA_ONLY", r[r.REGION_ALL = 1] = "REGION_ALL", r))(vs || {}), mo = /* @__PURE__ */ ((r) => (r.DNMS = "DNMS", r.GATEWAY = "GATEWAY", r))(mo || {}), xt = /* @__PURE__ */ ((r) => (r.HTTPS = "https", r.HTTP = "http", r.WSS = "wss", r.WS = "ws", r))(xt || {});
class Cm {
  constructor(e, t, i, s, n) {
    /**
     * 区号
     */
    y(this, "code");
    /**
     * 拼音
     */
    y(this, "pinyin");
    /**
     * 三位字母标识
     */
    y(this, "isoCode");
    /**
     * 地区名称
     */
    y(this, "areaName");
    /**
     * 两位字母标识
     */
    y(this, "domainAbbreviation");
    this.code = e, this.pinyin = t, this.isoCode = i, this.areaName = s, this.domainAbbreviation = n;
  }
}
var ps = /* @__PURE__ */ ((r) => (r[r.COMMON = 0] = "COMMON", r[r.SPECIAL = 1] = "SPECIAL", r[r.LAN = 2] = "LAN", r))(ps || {}), ki = /* @__PURE__ */ ((r) => (r[r.OK = 0] = "OK", r[r.Unkonwn = 1] = "Unkonwn", r[r.IllegalState = 2] = "IllegalState", r[r.NotImplemented = 3] = "NotImplemented", r[r.OutOfTimeRange = 4] = "OutOfTimeRange", r[r.RequestParamInvalid = 5] = "RequestParamInvalid", r[r.LostConfig = 6] = "LostConfig", r[r.ApiRequestFailed = 7] = "ApiRequestFailed", r[r.NotSupportFeature = 8] = "NotSupportFeature", r[r.TalkBusy = 9] = "TalkBusy", r[r.TalkConnectFailed = 10] = "TalkConnectFailed", r[r.P2PBusy = 11] = "P2PBusy", r[r.WakeUpTimeout = 12] = "WakeUpTimeout", r[r.DataChannelRspTimeout = 13] = "DataChannelRspTimeout", r[r.DataChannelCmdIdError = 14] = "DataChannelCmdIdError", r[r.DataChannelDataSizeError = 15] = "DataChannelDataSizeError", r[r.DataChannelInvalid = 16] = "DataChannelInvalid", r[r.DataChannelGetSDCardPicError = 17] = "DataChannelGetSDCardPicError", r[r.TokenInvalidError = 18] = "TokenInvalidError", r))(ki || {});
let pt = class {
  constructor(e, t) {
    y(this, "code");
    y(this, "message");
    this.code = e, this.message = t;
  }
  get name() {
    return "RuntimeException";
  }
  toString() {
    return this.code + ":" + this.name + ":" + this.message;
  }
};
class go extends pt {
  constructor(e) {
    super(18, e);
  }
  get name() {
    return "TokenInvalidException";
  }
}
let Xy = class extends pt {
  constructor(e) {
    super(2, e);
  }
  get name() {
    return "IllegalStateException";
  }
}, Lt = class extends pt {
  constructor(e) {
    super(5, e);
  }
  get name() {
    return "InvalidArgumentException";
  }
};
class ur extends pt {
  constructor(e) {
    super(7, e);
  }
  get name() {
    return "InvalidArgumentException";
  }
}
let Yy = class extends pt {
  constructor(e) {
    super(3, e);
  }
  get name() {
    return "NotImplementedException";
  }
};
class Rs extends pt {
  constructor(e) {
    super(6, e);
  }
  get name() {
    return "LostConfigException";
  }
}
class fn extends pt {
  constructor(e) {
    super(8, e);
  }
  get name() {
    return "UnsupportFeatureException";
  }
}
class H0 extends pt {
  constructor(e) {
    super(1, e);
  }
  get name() {
    return "UnknownException";
  }
}
const c6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  ApiRequestFailedException: ur,
  CloudPlatformTypeEnum: ps,
  Country: Cm,
  DataCenterDomainTypeEnum: mo,
  IllegalStateException: Xy,
  InvalidArgumentException: Lt,
  LocaleEnum: ed,
  LostConfigException: Rs,
  NotImplementedException: Yy,
  PlatformEnvEnum: hi,
  RegionTypeEnum: vs,
  RuntimeException: pt,
  RuntimeExceptionCode: ki,
  ServerSchemeEnum: xt,
  TokenInvalidException: go,
  UnknownException: H0,
  UnsupportFeatureException: fn
}, Symbol.toStringTag, { value: "Module" }));
var ko = { exports: {} };
function zy(r) {
  throw new Error('Could not dynamically require "' + r + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var wo = { exports: {} };
const jy = {}, Qy = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: jy
}, Symbol.toStringTag, { value: "Module" })), Rm = /* @__PURE__ */ Ny(Qy);
var vh;
function ge() {
  return vh || (vh = 1, function(r, e) {
    (function(t, i) {
      r.exports = i();
    })(le, function() {
      var t = t || function(i, s) {
        var n;
        if (typeof window < "u" && window.crypto && (n = window.crypto), typeof self < "u" && self.crypto && (n = self.crypto), typeof globalThis < "u" && globalThis.crypto && (n = globalThis.crypto), !n && typeof window < "u" && window.msCrypto && (n = window.msCrypto), !n && typeof le < "u" && le.crypto && (n = le.crypto), !n && typeof zy == "function")
          try {
            n = Rm;
          } catch {
          }
        var a = function() {
          if (n) {
            if (typeof n.getRandomValues == "function")
              try {
                return n.getRandomValues(new Uint32Array(1))[0];
              } catch {
              }
            if (typeof n.randomBytes == "function")
              try {
                return n.randomBytes(4).readInt32LE();
              } catch {
              }
          }
          throw new Error("Native crypto module could not be used to get secure random number.");
        }, o = Object.create || /* @__PURE__ */ function() {
          function _() {
          }
          return function(v) {
            var E;
            return _.prototype = v, E = new _(), _.prototype = null, E;
          };
        }(), c = {}, l = c.lib = {}, d = l.Base = /* @__PURE__ */ function() {
          return {
            /**
             * Creates a new object that inherits from this object.
             *
             * @param {Object} overrides Properties to copy into the new object.
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         field: 'value',
             *
             *         method: function () {
             *         }
             *     });
             */
            extend: function(_) {
              var v = o(this);
              return _ && v.mixIn(_), (!v.hasOwnProperty("init") || this.init === v.init) && (v.init = function() {
                v.$super.init.apply(this, arguments);
              }), v.init.prototype = v, v.$super = this, v;
            },
            /**
             * Extends this object and runs the init method.
             * Arguments to create() will be passed to init().
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var instance = MyType.create();
             */
            create: function() {
              var _ = this.extend();
              return _.init.apply(_, arguments), _;
            },
            /**
             * Initializes a newly created object.
             * Override this method to add some logic when your objects are created.
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         init: function () {
             *             // ...
             *         }
             *     });
             */
            init: function() {
            },
            /**
             * Copies properties into this object.
             *
             * @param {Object} properties The properties to mix in.
             *
             * @example
             *
             *     MyType.mixIn({
             *         field: 'value'
             *     });
             */
            mixIn: function(_) {
              for (var v in _)
                _.hasOwnProperty(v) && (this[v] = _[v]);
              _.hasOwnProperty("toString") && (this.toString = _.toString);
            },
            /**
             * Creates a copy of this object.
             *
             * @return {Object} The clone.
             *
             * @example
             *
             *     var clone = instance.clone();
             */
            clone: function() {
              return this.init.prototype.extend(this);
            }
          };
        }(), h = l.WordArray = d.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of 32-bit words.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.create();
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
           */
          init: function(_, v) {
            _ = this.words = _ || [], v != s ? this.sigBytes = v : this.sigBytes = _.length * 4;
          },
          /**
           * Converts this word array to a string.
           *
           * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
           *
           * @return {string} The stringified word array.
           *
           * @example
           *
           *     var string = wordArray + '';
           *     var string = wordArray.toString();
           *     var string = wordArray.toString(CryptoJS.enc.Utf8);
           */
          toString: function(_) {
            return (_ || f).stringify(this);
          },
          /**
           * Concatenates a word array to this word array.
           *
           * @param {WordArray} wordArray The word array to append.
           *
           * @return {WordArray} This word array.
           *
           * @example
           *
           *     wordArray1.concat(wordArray2);
           */
          concat: function(_) {
            var v = this.words, E = _.words, b = this.sigBytes, A = _.sigBytes;
            if (this.clamp(), b % 4)
              for (var C = 0; C < A; C++) {
                var I = E[C >>> 2] >>> 24 - C % 4 * 8 & 255;
                v[b + C >>> 2] |= I << 24 - (b + C) % 4 * 8;
              }
            else
              for (var L = 0; L < A; L += 4)
                v[b + L >>> 2] = E[L >>> 2];
            return this.sigBytes += A, this;
          },
          /**
           * Removes insignificant bits.
           *
           * @example
           *
           *     wordArray.clamp();
           */
          clamp: function() {
            var _ = this.words, v = this.sigBytes;
            _[v >>> 2] &= 4294967295 << 32 - v % 4 * 8, _.length = i.ceil(v / 4);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {WordArray} The clone.
           *
           * @example
           *
           *     var clone = wordArray.clone();
           */
          clone: function() {
            var _ = d.clone.call(this);
            return _.words = this.words.slice(0), _;
          },
          /**
           * Creates a word array filled with random bytes.
           *
           * @param {number} nBytes The number of random bytes to generate.
           *
           * @return {WordArray} The random word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.random(16);
           */
          random: function(_) {
            for (var v = [], E = 0; E < _; E += 4)
              v.push(a());
            return new h.init(v, _);
          }
        }), u = c.enc = {}, f = u.Hex = {
          /**
           * Converts a word array to a hex string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The hex string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
           */
          stringify: function(_) {
            for (var v = _.words, E = _.sigBytes, b = [], A = 0; A < E; A++) {
              var C = v[A >>> 2] >>> 24 - A % 4 * 8 & 255;
              b.push((C >>> 4).toString(16)), b.push((C & 15).toString(16));
            }
            return b.join("");
          },
          /**
           * Converts a hex string to a word array.
           *
           * @param {string} hexStr The hex string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
           */
          parse: function(_) {
            for (var v = _.length, E = [], b = 0; b < v; b += 2)
              E[b >>> 3] |= parseInt(_.substr(b, 2), 16) << 24 - b % 8 * 4;
            return new h.init(E, v / 2);
          }
        }, p = u.Latin1 = {
          /**
           * Converts a word array to a Latin1 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Latin1 string.
           *
           * @static
           *
           * @example
           *
           *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
           */
          stringify: function(_) {
            for (var v = _.words, E = _.sigBytes, b = [], A = 0; A < E; A++) {
              var C = v[A >>> 2] >>> 24 - A % 4 * 8 & 255;
              b.push(String.fromCharCode(C));
            }
            return b.join("");
          },
          /**
           * Converts a Latin1 string to a word array.
           *
           * @param {string} latin1Str The Latin1 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
           */
          parse: function(_) {
            for (var v = _.length, E = [], b = 0; b < v; b++)
              E[b >>> 2] |= (_.charCodeAt(b) & 255) << 24 - b % 4 * 8;
            return new h.init(E, v);
          }
        }, m = u.Utf8 = {
          /**
           * Converts a word array to a UTF-8 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-8 string.
           *
           * @static
           *
           * @example
           *
           *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
           */
          stringify: function(_) {
            try {
              return decodeURIComponent(escape(p.stringify(_)));
            } catch {
              throw new Error("Malformed UTF-8 data");
            }
          },
          /**
           * Converts a UTF-8 string to a word array.
           *
           * @param {string} utf8Str The UTF-8 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
           */
          parse: function(_) {
            return p.parse(unescape(encodeURIComponent(_)));
          }
        }, g = l.BufferedBlockAlgorithm = d.extend({
          /**
           * Resets this block algorithm's data buffer to its initial state.
           *
           * @example
           *
           *     bufferedBlockAlgorithm.reset();
           */
          reset: function() {
            this._data = new h.init(), this._nDataBytes = 0;
          },
          /**
           * Adds new data to this block algorithm's buffer.
           *
           * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
           *
           * @example
           *
           *     bufferedBlockAlgorithm._append('data');
           *     bufferedBlockAlgorithm._append(wordArray);
           */
          _append: function(_) {
            typeof _ == "string" && (_ = m.parse(_)), this._data.concat(_), this._nDataBytes += _.sigBytes;
          },
          /**
           * Processes available data blocks.
           *
           * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
           *
           * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
           *
           * @return {WordArray} The processed data.
           *
           * @example
           *
           *     var processedData = bufferedBlockAlgorithm._process();
           *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
           */
          _process: function(_) {
            var v, E = this._data, b = E.words, A = E.sigBytes, C = this.blockSize, I = C * 4, L = A / I;
            _ ? L = i.ceil(L) : L = i.max((L | 0) - this._minBufferSize, 0);
            var R = L * C, D = i.min(R * 4, A);
            if (R) {
              for (var M = 0; M < R; M += C)
                this._doProcessBlock(b, M);
              v = b.splice(0, R), E.sigBytes -= D;
            }
            return new h.init(v, D);
          },
          /**
           * Creates a copy of this object.
           *
           * @return {Object} The clone.
           *
           * @example
           *
           *     var clone = bufferedBlockAlgorithm.clone();
           */
          clone: function() {
            var _ = d.clone.call(this);
            return _._data = this._data.clone(), _;
          },
          _minBufferSize: 0
        });
        l.Hasher = g.extend({
          /**
           * Configuration options.
           */
          cfg: d.extend(),
          /**
           * Initializes a newly created hasher.
           *
           * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
           *
           * @example
           *
           *     var hasher = CryptoJS.algo.SHA256.create();
           */
          init: function(_) {
            this.cfg = this.cfg.extend(_), this.reset();
          },
          /**
           * Resets this hasher to its initial state.
           *
           * @example
           *
           *     hasher.reset();
           */
          reset: function() {
            g.reset.call(this), this._doReset();
          },
          /**
           * Updates this hasher with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {Hasher} This hasher.
           *
           * @example
           *
           *     hasher.update('message');
           *     hasher.update(wordArray);
           */
          update: function(_) {
            return this._append(_), this._process(), this;
          },
          /**
           * Finalizes the hash computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The hash.
           *
           * @example
           *
           *     var hash = hasher.finalize();
           *     var hash = hasher.finalize('message');
           *     var hash = hasher.finalize(wordArray);
           */
          finalize: function(_) {
            _ && this._append(_);
            var v = this._doFinalize();
            return v;
          },
          blockSize: 16,
          /**
           * Creates a shortcut function to a hasher's object interface.
           *
           * @param {Hasher} hasher The hasher to create a helper for.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
           */
          _createHelper: function(_) {
            return function(v, E) {
              return new _.init(E).finalize(v);
            };
          },
          /**
           * Creates a shortcut function to the HMAC's object interface.
           *
           * @param {Hasher} hasher The hasher to use in this HMAC helper.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
           */
          _createHmacHelper: function(_) {
            return function(v, E) {
              return new x.HMAC.init(_, E).finalize(v);
            };
          }
        });
        var x = c.algo = {};
        return c;
      }(Math);
      return t;
    });
  }(wo)), wo.exports;
}
var Mo = { exports: {} }, Eh;
function Zs() {
  return Eh || (Eh = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = i.enc;
        a.Base64 = {
          /**
           * Converts a word array to a Base64 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Base64 string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64.stringify(wordArray);
           */
          stringify: function(c) {
            var l = c.words, d = c.sigBytes, h = this._map;
            c.clamp();
            for (var u = [], f = 0; f < d; f += 3)
              for (var p = l[f >>> 2] >>> 24 - f % 4 * 8 & 255, m = l[f + 1 >>> 2] >>> 24 - (f + 1) % 4 * 8 & 255, g = l[f + 2 >>> 2] >>> 24 - (f + 2) % 4 * 8 & 255, x = p << 16 | m << 8 | g, _ = 0; _ < 4 && f + _ * 0.75 < d; _++)
                u.push(h.charAt(x >>> 6 * (3 - _) & 63));
            var v = h.charAt(64);
            if (v)
              for (; u.length % 4; )
                u.push(v);
            return u.join("");
          },
          /**
           * Converts a Base64 string to a word array.
           *
           * @param {string} base64Str The Base64 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64.parse(base64String);
           */
          parse: function(c) {
            var l = c.length, d = this._map, h = this._reverseMap;
            if (!h) {
              h = this._reverseMap = [];
              for (var u = 0; u < d.length; u++)
                h[d.charCodeAt(u)] = u;
            }
            var f = d.charAt(64);
            if (f) {
              var p = c.indexOf(f);
              p !== -1 && (l = p);
            }
            return o(c, l, h);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        };
        function o(c, l, d) {
          for (var h = [], u = 0, f = 0; f < l; f++)
            if (f % 4) {
              var p = d[c.charCodeAt(f - 1)] << f % 4 * 2, m = d[c.charCodeAt(f)] >>> 6 - f % 4 * 2, g = p | m;
              h[u >>> 2] |= g << 24 - u % 4 * 8, u++;
            }
          return n.create(h, u);
        }
      }(), t.enc.Base64;
    });
  }(Mo)), Mo.exports;
}
var Bo = { exports: {} }, Sh;
function $s() {
  return Sh || (Sh = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function(i) {
        var s = t, n = s.lib, a = n.WordArray, o = n.Hasher, c = s.algo, l = [];
        (function() {
          for (var m = 0; m < 64; m++)
            l[m] = i.abs(i.sin(m + 1)) * 4294967296 | 0;
        })();
        var d = c.MD5 = o.extend({
          _doReset: function() {
            this._hash = new a.init([
              1732584193,
              4023233417,
              2562383102,
              271733878
            ]);
          },
          _doProcessBlock: function(m, g) {
            for (var x = 0; x < 16; x++) {
              var _ = g + x, v = m[_];
              m[_] = (v << 8 | v >>> 24) & 16711935 | (v << 24 | v >>> 8) & 4278255360;
            }
            var E = this._hash.words, b = m[g + 0], A = m[g + 1], C = m[g + 2], I = m[g + 3], L = m[g + 4], R = m[g + 5], D = m[g + 6], M = m[g + 7], w = m[g + 8], N = m[g + 9], H = m[g + 10], G = m[g + 11], Z = m[g + 12], $ = m[g + 13], Y = m[g + 14], W = m[g + 15], k = E[0], P = E[1], B = E[2], O = E[3];
            k = h(k, P, B, O, b, 7, l[0]), O = h(O, k, P, B, A, 12, l[1]), B = h(B, O, k, P, C, 17, l[2]), P = h(P, B, O, k, I, 22, l[3]), k = h(k, P, B, O, L, 7, l[4]), O = h(O, k, P, B, R, 12, l[5]), B = h(B, O, k, P, D, 17, l[6]), P = h(P, B, O, k, M, 22, l[7]), k = h(k, P, B, O, w, 7, l[8]), O = h(O, k, P, B, N, 12, l[9]), B = h(B, O, k, P, H, 17, l[10]), P = h(P, B, O, k, G, 22, l[11]), k = h(k, P, B, O, Z, 7, l[12]), O = h(O, k, P, B, $, 12, l[13]), B = h(B, O, k, P, Y, 17, l[14]), P = h(P, B, O, k, W, 22, l[15]), k = u(k, P, B, O, A, 5, l[16]), O = u(O, k, P, B, D, 9, l[17]), B = u(B, O, k, P, G, 14, l[18]), P = u(P, B, O, k, b, 20, l[19]), k = u(k, P, B, O, R, 5, l[20]), O = u(O, k, P, B, H, 9, l[21]), B = u(B, O, k, P, W, 14, l[22]), P = u(P, B, O, k, L, 20, l[23]), k = u(k, P, B, O, N, 5, l[24]), O = u(O, k, P, B, Y, 9, l[25]), B = u(B, O, k, P, I, 14, l[26]), P = u(P, B, O, k, w, 20, l[27]), k = u(k, P, B, O, $, 5, l[28]), O = u(O, k, P, B, C, 9, l[29]), B = u(B, O, k, P, M, 14, l[30]), P = u(P, B, O, k, Z, 20, l[31]), k = f(k, P, B, O, R, 4, l[32]), O = f(O, k, P, B, w, 11, l[33]), B = f(B, O, k, P, G, 16, l[34]), P = f(P, B, O, k, Y, 23, l[35]), k = f(k, P, B, O, A, 4, l[36]), O = f(O, k, P, B, L, 11, l[37]), B = f(B, O, k, P, M, 16, l[38]), P = f(P, B, O, k, H, 23, l[39]), k = f(k, P, B, O, $, 4, l[40]), O = f(O, k, P, B, b, 11, l[41]), B = f(B, O, k, P, I, 16, l[42]), P = f(P, B, O, k, D, 23, l[43]), k = f(k, P, B, O, N, 4, l[44]), O = f(O, k, P, B, Z, 11, l[45]), B = f(B, O, k, P, W, 16, l[46]), P = f(P, B, O, k, C, 23, l[47]), k = p(k, P, B, O, b, 6, l[48]), O = p(O, k, P, B, M, 10, l[49]), B = p(B, O, k, P, Y, 15, l[50]), P = p(P, B, O, k, R, 21, l[51]), k = p(k, P, B, O, Z, 6, l[52]), O = p(O, k, P, B, I, 10, l[53]), B = p(B, O, k, P, H, 15, l[54]), P = p(P, B, O, k, A, 21, l[55]), k = p(k, P, B, O, w, 6, l[56]), O = p(O, k, P, B, W, 10, l[57]), B = p(B, O, k, P, D, 15, l[58]), P = p(P, B, O, k, $, 21, l[59]), k = p(k, P, B, O, L, 6, l[60]), O = p(O, k, P, B, G, 10, l[61]), B = p(B, O, k, P, C, 15, l[62]), P = p(P, B, O, k, N, 21, l[63]), E[0] = E[0] + k | 0, E[1] = E[1] + P | 0, E[2] = E[2] + B | 0, E[3] = E[3] + O | 0;
          },
          _doFinalize: function() {
            var m = this._data, g = m.words, x = this._nDataBytes * 8, _ = m.sigBytes * 8;
            g[_ >>> 5] |= 128 << 24 - _ % 32;
            var v = i.floor(x / 4294967296), E = x;
            g[(_ + 64 >>> 9 << 4) + 15] = (v << 8 | v >>> 24) & 16711935 | (v << 24 | v >>> 8) & 4278255360, g[(_ + 64 >>> 9 << 4) + 14] = (E << 8 | E >>> 24) & 16711935 | (E << 24 | E >>> 8) & 4278255360, m.sigBytes = (g.length + 1) * 4, this._process();
            for (var b = this._hash, A = b.words, C = 0; C < 4; C++) {
              var I = A[C];
              A[C] = (I << 8 | I >>> 24) & 16711935 | (I << 24 | I >>> 8) & 4278255360;
            }
            return b;
          },
          clone: function() {
            var m = o.clone.call(this);
            return m._hash = this._hash.clone(), m;
          }
        });
        function h(m, g, x, _, v, E, b) {
          var A = m + (g & x | ~g & _) + v + b;
          return (A << E | A >>> 32 - E) + g;
        }
        function u(m, g, x, _, v, E, b) {
          var A = m + (g & _ | x & ~_) + v + b;
          return (A << E | A >>> 32 - E) + g;
        }
        function f(m, g, x, _, v, E, b) {
          var A = m + (g ^ x ^ _) + v + b;
          return (A << E | A >>> 32 - E) + g;
        }
        function p(m, g, x, _, v, E, b) {
          var A = m + (x ^ (g | ~_)) + v + b;
          return (A << E | A >>> 32 - E) + g;
        }
        s.MD5 = o._createHelper(d), s.HmacMD5 = o._createHmacHelper(d);
      }(Math), t.MD5;
    });
  }(Bo)), Bo.exports;
}
var Fo = { exports: {} }, Oo = { exports: {} }, Th;
function Im() {
  return Th || (Th = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = s.Hasher, o = i.algo, c = [], l = o.SHA1 = a.extend({
          _doReset: function() {
            this._hash = new n.init([
              1732584193,
              4023233417,
              2562383102,
              271733878,
              3285377520
            ]);
          },
          _doProcessBlock: function(d, h) {
            for (var u = this._hash.words, f = u[0], p = u[1], m = u[2], g = u[3], x = u[4], _ = 0; _ < 80; _++) {
              if (_ < 16)
                c[_] = d[h + _] | 0;
              else {
                var v = c[_ - 3] ^ c[_ - 8] ^ c[_ - 14] ^ c[_ - 16];
                c[_] = v << 1 | v >>> 31;
              }
              var E = (f << 5 | f >>> 27) + x + c[_];
              _ < 20 ? E += (p & m | ~p & g) + 1518500249 : _ < 40 ? E += (p ^ m ^ g) + 1859775393 : _ < 60 ? E += (p & m | p & g | m & g) - 1894007588 : E += (p ^ m ^ g) - 899497514, x = g, g = m, m = p << 30 | p >>> 2, p = f, f = E;
            }
            u[0] = u[0] + f | 0, u[1] = u[1] + p | 0, u[2] = u[2] + m | 0, u[3] = u[3] + g | 0, u[4] = u[4] + x | 0;
          },
          _doFinalize: function() {
            var d = this._data, h = d.words, u = this._nDataBytes * 8, f = d.sigBytes * 8;
            return h[f >>> 5] |= 128 << 24 - f % 32, h[(f + 64 >>> 9 << 4) + 14] = Math.floor(u / 4294967296), h[(f + 64 >>> 9 << 4) + 15] = u, d.sigBytes = h.length * 4, this._process(), this._hash;
          },
          clone: function() {
            var d = a.clone.call(this);
            return d._hash = this._hash.clone(), d;
          }
        });
        i.SHA1 = a._createHelper(l), i.HmacSHA1 = a._createHmacHelper(l);
      }(), t.SHA1;
    });
  }(Oo)), Oo.exports;
}
var No = { exports: {} }, bh;
function td() {
  return bh || (bh = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      (function() {
        var i = t, s = i.lib, n = s.Base, a = i.enc, o = a.Utf8, c = i.algo;
        c.HMAC = n.extend({
          /**
           * Initializes a newly created HMAC.
           *
           * @param {Hasher} hasher The hash algorithm to use.
           * @param {WordArray|string} key The secret key.
           *
           * @example
           *
           *     var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
           */
          init: function(l, d) {
            l = this._hasher = new l.init(), typeof d == "string" && (d = o.parse(d));
            var h = l.blockSize, u = h * 4;
            d.sigBytes > u && (d = l.finalize(d)), d.clamp();
            for (var f = this._oKey = d.clone(), p = this._iKey = d.clone(), m = f.words, g = p.words, x = 0; x < h; x++)
              m[x] ^= 1549556828, g[x] ^= 909522486;
            f.sigBytes = p.sigBytes = u, this.reset();
          },
          /**
           * Resets this HMAC to its initial state.
           *
           * @example
           *
           *     hmacHasher.reset();
           */
          reset: function() {
            var l = this._hasher;
            l.reset(), l.update(this._iKey);
          },
          /**
           * Updates this HMAC with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {HMAC} This HMAC instance.
           *
           * @example
           *
           *     hmacHasher.update('message');
           *     hmacHasher.update(wordArray);
           */
          update: function(l) {
            return this._hasher.update(l), this;
          },
          /**
           * Finalizes the HMAC computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The HMAC.
           *
           * @example
           *
           *     var hmac = hmacHasher.finalize();
           *     var hmac = hmacHasher.finalize('message');
           *     var hmac = hmacHasher.finalize(wordArray);
           */
          finalize: function(l) {
            var d = this._hasher, h = d.finalize(l);
            d.reset();
            var u = d.finalize(this._oKey.clone().concat(h));
            return u;
          }
        });
      })();
    });
  }(No)), No.exports;
}
var Ah;
function Es() {
  return Ah || (Ah = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Im(), td());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.Base, a = s.WordArray, o = i.algo, c = o.MD5, l = o.EvpKDF = n.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hash algorithm to use. Default: MD5
           * @property {number} iterations The number of iterations to perform. Default: 1
           */
          cfg: n.extend({
            keySize: 128 / 32,
            hasher: c,
            iterations: 1
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.EvpKDF.create();
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
           */
          init: function(d) {
            this.cfg = this.cfg.extend(d);
          },
          /**
           * Derives a key from a password.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(d, h) {
            for (var u, f = this.cfg, p = f.hasher.create(), m = a.create(), g = m.words, x = f.keySize, _ = f.iterations; g.length < x; ) {
              u && p.update(u), u = p.update(d).finalize(h), p.reset();
              for (var v = 1; v < _; v++)
                u = p.finalize(u), p.reset();
              m.concat(u);
            }
            return m.sigBytes = x * 4, m;
          }
        });
        i.EvpKDF = function(d, h, u) {
          return l.create(u).compute(d, h);
        };
      }(), t.EvpKDF;
    });
  }(Fo)), Fo.exports;
}
var Go = { exports: {} }, Ch;
function ot() {
  return Ch || (Ch = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Es());
    })(le, function(t) {
      t.lib.Cipher || function(i) {
        var s = t, n = s.lib, a = n.Base, o = n.WordArray, c = n.BufferedBlockAlgorithm, l = s.enc;
        l.Utf8;
        var d = l.Base64, h = s.algo, u = h.EvpKDF, f = n.Cipher = c.extend({
          /**
           * Configuration options.
           *
           * @property {WordArray} iv The IV to use for this operation.
           */
          cfg: a.extend(),
          /**
           * Creates this cipher in encryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
           */
          createEncryptor: function(R, D) {
            return this.create(this._ENC_XFORM_MODE, R, D);
          },
          /**
           * Creates this cipher in decryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
           */
          createDecryptor: function(R, D) {
            return this.create(this._DEC_XFORM_MODE, R, D);
          },
          /**
           * Initializes a newly created cipher.
           *
           * @param {number} xformMode Either the encryption or decryption transormation mode constant.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
           */
          init: function(R, D, M) {
            this.cfg = this.cfg.extend(M), this._xformMode = R, this._key = D, this.reset();
          },
          /**
           * Resets this cipher to its initial state.
           *
           * @example
           *
           *     cipher.reset();
           */
          reset: function() {
            c.reset.call(this), this._doReset();
          },
          /**
           * Adds data to be encrypted or decrypted.
           *
           * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
           *
           * @return {WordArray} The data after processing.
           *
           * @example
           *
           *     var encrypted = cipher.process('data');
           *     var encrypted = cipher.process(wordArray);
           */
          process: function(R) {
            return this._append(R), this._process();
          },
          /**
           * Finalizes the encryption or decryption process.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
           *
           * @return {WordArray} The data after final processing.
           *
           * @example
           *
           *     var encrypted = cipher.finalize();
           *     var encrypted = cipher.finalize('data');
           *     var encrypted = cipher.finalize(wordArray);
           */
          finalize: function(R) {
            R && this._append(R);
            var D = this._doFinalize();
            return D;
          },
          keySize: 128 / 32,
          ivSize: 128 / 32,
          _ENC_XFORM_MODE: 1,
          _DEC_XFORM_MODE: 2,
          /**
           * Creates shortcut functions to a cipher's object interface.
           *
           * @param {Cipher} cipher The cipher to create a helper for.
           *
           * @return {Object} An object with encrypt and decrypt shortcut functions.
           *
           * @static
           *
           * @example
           *
           *     var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
           */
          _createHelper: /* @__PURE__ */ function() {
            function R(D) {
              return typeof D == "string" ? L : A;
            }
            return function(D) {
              return {
                encrypt: function(M, w, N) {
                  return R(w).encrypt(D, M, w, N);
                },
                decrypt: function(M, w, N) {
                  return R(w).decrypt(D, M, w, N);
                }
              };
            };
          }()
        });
        n.StreamCipher = f.extend({
          _doFinalize: function() {
            var R = this._process(!0);
            return R;
          },
          blockSize: 1
        });
        var p = s.mode = {}, m = n.BlockCipherMode = a.extend({
          /**
           * Creates this mode for encryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
           */
          createEncryptor: function(R, D) {
            return this.Encryptor.create(R, D);
          },
          /**
           * Creates this mode for decryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
           */
          createDecryptor: function(R, D) {
            return this.Decryptor.create(R, D);
          },
          /**
           * Initializes a newly created mode.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
           */
          init: function(R, D) {
            this._cipher = R, this._iv = D;
          }
        }), g = p.CBC = function() {
          var R = m.extend();
          R.Encryptor = R.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(M, w) {
              var N = this._cipher, H = N.blockSize;
              D.call(this, M, w, H), N.encryptBlock(M, w), this._prevBlock = M.slice(w, w + H);
            }
          }), R.Decryptor = R.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(M, w) {
              var N = this._cipher, H = N.blockSize, G = M.slice(w, w + H);
              N.decryptBlock(M, w), D.call(this, M, w, H), this._prevBlock = G;
            }
          });
          function D(M, w, N) {
            var H, G = this._iv;
            G ? (H = G, this._iv = i) : H = this._prevBlock;
            for (var Z = 0; Z < N; Z++)
              M[w + Z] ^= H[Z];
          }
          return R;
        }(), x = s.pad = {}, _ = x.Pkcs7 = {
          /**
           * Pads data using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to pad.
           * @param {number} blockSize The multiple that the data should be padded to.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.pad(wordArray, 4);
           */
          pad: function(R, D) {
            for (var M = D * 4, w = M - R.sigBytes % M, N = w << 24 | w << 16 | w << 8 | w, H = [], G = 0; G < w; G += 4)
              H.push(N);
            var Z = o.create(H, w);
            R.concat(Z);
          },
          /**
           * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to unpad.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.unpad(wordArray);
           */
          unpad: function(R) {
            var D = R.words[R.sigBytes - 1 >>> 2] & 255;
            R.sigBytes -= D;
          }
        };
        n.BlockCipher = f.extend({
          /**
           * Configuration options.
           *
           * @property {Mode} mode The block mode to use. Default: CBC
           * @property {Padding} padding The padding strategy to use. Default: Pkcs7
           */
          cfg: f.cfg.extend({
            mode: g,
            padding: _
          }),
          reset: function() {
            var R;
            f.reset.call(this);
            var D = this.cfg, M = D.iv, w = D.mode;
            this._xformMode == this._ENC_XFORM_MODE ? R = w.createEncryptor : (R = w.createDecryptor, this._minBufferSize = 1), this._mode && this._mode.__creator == R ? this._mode.init(this, M && M.words) : (this._mode = R.call(w, this, M && M.words), this._mode.__creator = R);
          },
          _doProcessBlock: function(R, D) {
            this._mode.processBlock(R, D);
          },
          _doFinalize: function() {
            var R, D = this.cfg.padding;
            return this._xformMode == this._ENC_XFORM_MODE ? (D.pad(this._data, this.blockSize), R = this._process(!0)) : (R = this._process(!0), D.unpad(R)), R;
          },
          blockSize: 128 / 32
        });
        var v = n.CipherParams = a.extend({
          /**
           * Initializes a newly created cipher params object.
           *
           * @param {Object} cipherParams An object with any of the possible cipher parameters.
           *
           * @example
           *
           *     var cipherParams = CryptoJS.lib.CipherParams.create({
           *         ciphertext: ciphertextWordArray,
           *         key: keyWordArray,
           *         iv: ivWordArray,
           *         salt: saltWordArray,
           *         algorithm: CryptoJS.algo.AES,
           *         mode: CryptoJS.mode.CBC,
           *         padding: CryptoJS.pad.PKCS7,
           *         blockSize: 4,
           *         formatter: CryptoJS.format.OpenSSL
           *     });
           */
          init: function(R) {
            this.mixIn(R);
          },
          /**
           * Converts this cipher params object to a string.
           *
           * @param {Format} formatter (Optional) The formatting strategy to use.
           *
           * @return {string} The stringified cipher params.
           *
           * @throws Error If neither the formatter nor the default formatter is set.
           *
           * @example
           *
           *     var string = cipherParams + '';
           *     var string = cipherParams.toString();
           *     var string = cipherParams.toString(CryptoJS.format.OpenSSL);
           */
          toString: function(R) {
            return (R || this.formatter).stringify(this);
          }
        }), E = s.format = {}, b = E.OpenSSL = {
          /**
           * Converts a cipher params object to an OpenSSL-compatible string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The OpenSSL-compatible string.
           *
           * @static
           *
           * @example
           *
           *     var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
           */
          stringify: function(R) {
            var D, M = R.ciphertext, w = R.salt;
            return w ? D = o.create([1398893684, 1701076831]).concat(w).concat(M) : D = M, D.toString(d);
          },
          /**
           * Converts an OpenSSL-compatible string to a cipher params object.
           *
           * @param {string} openSSLStr The OpenSSL-compatible string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
           */
          parse: function(R) {
            var D, M = d.parse(R), w = M.words;
            return w[0] == 1398893684 && w[1] == 1701076831 && (D = o.create(w.slice(2, 4)), w.splice(0, 4), M.sigBytes -= 16), v.create({ ciphertext: M, salt: D });
          }
        }, A = n.SerializableCipher = a.extend({
          /**
           * Configuration options.
           *
           * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
           */
          cfg: a.extend({
            format: b
          }),
          /**
           * Encrypts a message.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(R, D, M, w) {
            w = this.cfg.extend(w);
            var N = R.createEncryptor(M, w), H = N.finalize(D), G = N.cfg;
            return v.create({
              ciphertext: H,
              key: M,
              iv: G.iv,
              algorithm: R,
              mode: G.mode,
              padding: G.padding,
              blockSize: R.blockSize,
              formatter: w.format
            });
          },
          /**
           * Decrypts serialized ciphertext.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(R, D, M, w) {
            w = this.cfg.extend(w), D = this._parse(D, w.format);
            var N = R.createDecryptor(M, w).finalize(D.ciphertext);
            return N;
          },
          /**
           * Converts serialized ciphertext to CipherParams,
           * else assumed CipherParams already and returns ciphertext unchanged.
           *
           * @param {CipherParams|string} ciphertext The ciphertext.
           * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
           *
           * @return {CipherParams} The unserialized ciphertext.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
           */
          _parse: function(R, D) {
            return typeof R == "string" ? D.parse(R, this) : R;
          }
        }), C = s.kdf = {}, I = C.OpenSSL = {
          /**
           * Derives a key and IV from a password.
           *
           * @param {string} password The password to derive from.
           * @param {number} keySize The size in words of the key to generate.
           * @param {number} ivSize The size in words of the IV to generate.
           * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
           *
           * @return {CipherParams} A cipher params object with the key, IV, and salt.
           *
           * @static
           *
           * @example
           *
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
           */
          execute: function(R, D, M, w, N) {
            if (w || (w = o.random(64 / 8)), N)
              var H = u.create({ keySize: D + M, hasher: N }).compute(R, w);
            else
              var H = u.create({ keySize: D + M }).compute(R, w);
            var G = o.create(H.words.slice(D), M * 4);
            return H.sigBytes = D * 4, v.create({ key: H, iv: G, salt: w });
          }
        }, L = n.PasswordBasedCipher = A.extend({
          /**
           * Configuration options.
           *
           * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
           */
          cfg: A.cfg.extend({
            kdf: I
          }),
          /**
           * Encrypts a message using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(R, D, M, w) {
            w = this.cfg.extend(w);
            var N = w.kdf.execute(M, R.keySize, R.ivSize, w.salt, w.hasher);
            w.iv = N.iv;
            var H = A.encrypt.call(this, R, D, N.key, w);
            return H.mixIn(N), H;
          },
          /**
           * Decrypts serialized ciphertext using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(R, D, M, w) {
            w = this.cfg.extend(w), D = this._parse(D, w.format);
            var N = w.kdf.execute(M, R.keySize, R.ivSize, D.salt, w.hasher);
            w.iv = N.iv;
            var H = A.decrypt.call(this, R, D, N.key, w);
            return H;
          }
        });
      }();
    });
  }(Go)), Go.exports;
}
var Rh;
function Lm() {
  return Rh || (Rh = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.BlockCipher, a = i.algo, o = [], c = [], l = [], d = [], h = [], u = [], f = [], p = [], m = [], g = [];
        (function() {
          for (var v = [], E = 0; E < 256; E++)
            E < 128 ? v[E] = E << 1 : v[E] = E << 1 ^ 283;
          for (var b = 0, A = 0, E = 0; E < 256; E++) {
            var C = A ^ A << 1 ^ A << 2 ^ A << 3 ^ A << 4;
            C = C >>> 8 ^ C & 255 ^ 99, o[b] = C, c[C] = b;
            var I = v[b], L = v[I], R = v[L], D = v[C] * 257 ^ C * 16843008;
            l[b] = D << 24 | D >>> 8, d[b] = D << 16 | D >>> 16, h[b] = D << 8 | D >>> 24, u[b] = D;
            var D = R * 16843009 ^ L * 65537 ^ I * 257 ^ b * 16843008;
            f[C] = D << 24 | D >>> 8, p[C] = D << 16 | D >>> 16, m[C] = D << 8 | D >>> 24, g[C] = D, b ? (b = I ^ v[v[v[R ^ I]]], A ^= v[v[A]]) : b = A = 1;
          }
        })();
        var x = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], _ = a.AES = n.extend({
          _doReset: function() {
            var v;
            if (!(this._nRounds && this._keyPriorReset === this._key)) {
              for (var E = this._keyPriorReset = this._key, b = E.words, A = E.sigBytes / 4, C = this._nRounds = A + 6, I = (C + 1) * 4, L = this._keySchedule = [], R = 0; R < I; R++)
                R < A ? L[R] = b[R] : (v = L[R - 1], R % A ? A > 6 && R % A == 4 && (v = o[v >>> 24] << 24 | o[v >>> 16 & 255] << 16 | o[v >>> 8 & 255] << 8 | o[v & 255]) : (v = v << 8 | v >>> 24, v = o[v >>> 24] << 24 | o[v >>> 16 & 255] << 16 | o[v >>> 8 & 255] << 8 | o[v & 255], v ^= x[R / A | 0] << 24), L[R] = L[R - A] ^ v);
              for (var D = this._invKeySchedule = [], M = 0; M < I; M++) {
                var R = I - M;
                if (M % 4)
                  var v = L[R];
                else
                  var v = L[R - 4];
                M < 4 || R <= 4 ? D[M] = v : D[M] = f[o[v >>> 24]] ^ p[o[v >>> 16 & 255]] ^ m[o[v >>> 8 & 255]] ^ g[o[v & 255]];
              }
            }
          },
          encryptBlock: function(v, E) {
            this._doCryptBlock(v, E, this._keySchedule, l, d, h, u, o);
          },
          decryptBlock: function(v, E) {
            var b = v[E + 1];
            v[E + 1] = v[E + 3], v[E + 3] = b, this._doCryptBlock(v, E, this._invKeySchedule, f, p, m, g, c);
            var b = v[E + 1];
            v[E + 1] = v[E + 3], v[E + 3] = b;
          },
          _doCryptBlock: function(v, E, b, A, C, I, L, R) {
            for (var D = this._nRounds, M = v[E] ^ b[0], w = v[E + 1] ^ b[1], N = v[E + 2] ^ b[2], H = v[E + 3] ^ b[3], G = 4, Z = 1; Z < D; Z++) {
              var $ = A[M >>> 24] ^ C[w >>> 16 & 255] ^ I[N >>> 8 & 255] ^ L[H & 255] ^ b[G++], Y = A[w >>> 24] ^ C[N >>> 16 & 255] ^ I[H >>> 8 & 255] ^ L[M & 255] ^ b[G++], W = A[N >>> 24] ^ C[H >>> 16 & 255] ^ I[M >>> 8 & 255] ^ L[w & 255] ^ b[G++], k = A[H >>> 24] ^ C[M >>> 16 & 255] ^ I[w >>> 8 & 255] ^ L[N & 255] ^ b[G++];
              M = $, w = Y, N = W, H = k;
            }
            var $ = (R[M >>> 24] << 24 | R[w >>> 16 & 255] << 16 | R[N >>> 8 & 255] << 8 | R[H & 255]) ^ b[G++], Y = (R[w >>> 24] << 24 | R[N >>> 16 & 255] << 16 | R[H >>> 8 & 255] << 8 | R[M & 255]) ^ b[G++], W = (R[N >>> 24] << 24 | R[H >>> 16 & 255] << 16 | R[M >>> 8 & 255] << 8 | R[w & 255]) ^ b[G++], k = (R[H >>> 24] << 24 | R[M >>> 16 & 255] << 16 | R[w >>> 8 & 255] << 8 | R[N & 255]) ^ b[G++];
            v[E] = $, v[E + 1] = Y, v[E + 2] = W, v[E + 3] = k;
          },
          keySize: 256 / 32
        });
        i.AES = n._createHelper(_);
      }(), t.AES;
    });
  }(ko)), ko.exports;
}
Lm();
var Jy = { exports: {} };
(function(r, e) {
  (function(t, i) {
    r.exports = i(ge());
  })(le, function(t) {
    return t.enc.Utf8;
  });
})(Jy);
var qy = { exports: {} };
(function(r, e) {
  (function(t, i, s) {
    r.exports = i(ge(), ot());
  })(le, function(t) {
    return t.pad.Pkcs7;
  });
})(qy);
var e2 = { exports: {} };
(function(r, e) {
  (function(t, i) {
    r.exports = i(ge());
  })(le, function(t) {
    return t.enc.Hex;
  });
})(e2);
var Uo = { exports: {} }, Ih;
function Cn() {
  return Ih || (Ih = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function(i) {
        var s = t, n = s.lib, a = n.Base, o = n.WordArray, c = s.x64 = {};
        c.Word = a.extend({
          /**
           * Initializes a newly created 64-bit word.
           *
           * @param {number} high The high 32 bits.
           * @param {number} low The low 32 bits.
           *
           * @example
           *
           *     var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
           */
          init: function(l, d) {
            this.high = l, this.low = d;
          }
          /**
           * Bitwise NOTs this word.
           *
           * @return {X64Word} A new x64-Word object after negating.
           *
           * @example
           *
           *     var negated = x64Word.not();
           */
          // not: function () {
          // var high = ~this.high;
          // var low = ~this.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ANDs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to AND with this word.
           *
           * @return {X64Word} A new x64-Word object after ANDing.
           *
           * @example
           *
           *     var anded = x64Word.and(anotherX64Word);
           */
          // and: function (word) {
          // var high = this.high & word.high;
          // var low = this.low & word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to OR with this word.
           *
           * @return {X64Word} A new x64-Word object after ORing.
           *
           * @example
           *
           *     var ored = x64Word.or(anotherX64Word);
           */
          // or: function (word) {
          // var high = this.high | word.high;
          // var low = this.low | word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise XORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to XOR with this word.
           *
           * @return {X64Word} A new x64-Word object after XORing.
           *
           * @example
           *
           *     var xored = x64Word.xor(anotherX64Word);
           */
          // xor: function (word) {
          // var high = this.high ^ word.high;
          // var low = this.low ^ word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the left.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftL(25);
           */
          // shiftL: function (n) {
          // if (n < 32) {
          // var high = (this.high << n) | (this.low >>> (32 - n));
          // var low = this.low << n;
          // } else {
          // var high = this.low << (n - 32);
          // var low = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the right.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftR(7);
           */
          // shiftR: function (n) {
          // if (n < 32) {
          // var low = (this.low >>> n) | (this.high << (32 - n));
          // var high = this.high >>> n;
          // } else {
          // var low = this.high >>> (n - 32);
          // var high = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Rotates this word n bits to the left.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotL(25);
           */
          // rotL: function (n) {
          // return this.shiftL(n).or(this.shiftR(64 - n));
          // },
          /**
           * Rotates this word n bits to the right.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotR(7);
           */
          // rotR: function (n) {
          // return this.shiftR(n).or(this.shiftL(64 - n));
          // },
          /**
           * Adds this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to add with this word.
           *
           * @return {X64Word} A new x64-Word object after adding.
           *
           * @example
           *
           *     var added = x64Word.add(anotherX64Word);
           */
          // add: function (word) {
          // var low = (this.low + word.low) | 0;
          // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
          // var high = (this.high + word.high + carry) | 0;
          // return X64Word.create(high, low);
          // }
        }), c.WordArray = a.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.x64.WordArray.create();
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ]);
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ], 10);
           */
          init: function(l, d) {
            l = this.words = l || [], d != i ? this.sigBytes = d : this.sigBytes = l.length * 8;
          },
          /**
           * Converts this 64-bit word array to a 32-bit word array.
           *
           * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
           *
           * @example
           *
           *     var x32WordArray = x64WordArray.toX32();
           */
          toX32: function() {
            for (var l = this.words, d = l.length, h = [], u = 0; u < d; u++) {
              var f = l[u];
              h.push(f.high), h.push(f.low);
            }
            return o.create(h, this.sigBytes);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {X64WordArray} The clone.
           *
           * @example
           *
           *     var clone = x64WordArray.clone();
           */
          clone: function() {
            for (var l = a.clone.call(this), d = l.words = this.words.slice(0), h = d.length, u = 0; u < h; u++)
              d[u] = d[u].clone();
            return l;
          }
        });
      }(), t;
    });
  }(Uo)), Uo.exports;
}
var t2 = Cn();
const Ui = /* @__PURE__ */ Fr(t2), Lh = 32, Dh = Ui.enc.Hex.parse(new Array(32).fill(0).join(""));
class i2 {
  constructor(e) {
    y(this, "key", "");
    const t = new Uint8Array(Lh), i = new TextEncoder().encode(e).slice(0, Lh);
    t.set(i, 0), this.key = Ui.enc.Utf8.parse(new TextDecoder().decode(t));
  }
  encrypt(e) {
    return Ui.AES.encrypt(e, this.key, {
      iv: Dh,
      mode: Ui.mode.CBC,
      padding: Ui.pad.Pkcs7
    }).toString();
  }
  decrypt(e) {
    return Ui.AES.decrypt(e, this.key, {
      iv: Dh,
      mode: Ui.mode.CBC,
      padding: Ui.pad.Pkcs7
    }).toString(Ui.enc.Utf8);
  }
}
const s2 = atob("UlRDWF9XRUJfQ1JZUFRP");
class r2 {
  constructor(e) {
    y(this, "crypto");
    y(this, "storage");
    this.crypto = new i2(s2), this.storage = e;
  }
  get length() {
    return this.storage.length;
  }
  clear() {
    this.storage.clear();
  }
  key(e) {
    return this.storage.key(e);
  }
  setItem(e, t) {
    const i = this.crypto.encrypt(e), s = this.crypto.encrypt(JSON.stringify(t));
    this.storage.setItem(i, s);
  }
  getItem(e) {
    const t = this.crypto.encrypt(e), i = this.storage.getItem(t);
    if (!i) return i;
    try {
      return JSON.parse(this.crypto.decrypt(i));
    } catch {
      return null;
    }
  }
  removeItem(e) {
    const t = this.crypto.encrypt(e);
    this.storage.removeItem(t);
  }
}
const se = new r2(window.localStorage), Vo = "RTCX_PLATFORM_ENV_KEY", Wo = "RTCX_APP_KEY_KEY", Ho = "RTCX_APP_SECRET_KEY", Zo = "RTCX_DATA_CENTER_SCHEMA_KEY", $o = "RTCX_DATA_CENTER_DOMAIN_KEY", Ko = "DATA_CENTER_DOMAIN_TYPE_KEY", Xo = "DOMAIN_AUTO_WITH_AK_KEY", Yo = "RTCX_SIGNALING_SCHEMA_KEY", zo = "RTCX_SIGNALING_DOMAIN_KEY", jo = "RTCX_APP_LOCALE_KEY", Qo = "RTCX_APP_COUNTRY_KEY", Jo = "RTCX_REGION_TYPE_KEY", qo = "RTCX_SPECIAL_APP_KEY_KEY", el = "RTCX_SPECIAL_APP_SECRET_KEY", tl = "RTCX_SPECIAL_DATA_CENTER_SCHEMA_KEY", il = "RTCX_SPECIAL_DATA_CENTER_DOMAIN_KEY", sl = "RTCX_SPECIAL_SIGNALING_SCHEMA_KEY", rl = "RTCX_SPECIAL_SIGNALING_DOMAIN_KEY";
class n2 {
  get platformEnv() {
    return se.getItem(Vo) || hi.PROD;
  }
  set platformEnv(e) {
    se.setItem(Vo, e);
  }
  get appKey() {
    return se.getItem(Wo) || "";
  }
  set appKey(e) {
    e && se.setItem(Wo, e);
  }
  get appSecret() {
    return se.getItem(Ho) || "";
  }
  set appSecret(e) {
    e && se.setItem(Ho, e);
  }
  get dataCenterSchema() {
    return se.getItem(Zo) || xt.HTTPS;
  }
  set dataCenterSchema(e) {
    e && se.setItem(Zo, e);
  }
  get dataCenterDomain() {
    return se.getItem($o) || "";
  }
  set dataCenterDomain(e) {
    e && se.setItem($o, e);
  }
  get dataCenterDomainType() {
    return se.getItem(Ko) || "";
  }
  set dataCenterDomainType(e) {
    e && se.setItem(Ko, e);
  }
  get domainAutoWithAK() {
    return se.getItem(Xo) ?? !0;
  }
  set domainAutoWithAK(e) {
    e && se.setItem(Xo, e);
  }
  get signalingSchema() {
    return se.getItem(Yo) || xt.WSS;
  }
  set signalingSchema(e) {
    e && se.setItem(Yo, e);
  }
  get signalingDomain() {
    return se.getItem(zo) || "";
  }
  set signalingDomain(e) {
    e && se.setItem(zo, e);
  }
  get locale() {
    return se.getItem(jo) || (navigator.language ? navigator.language.replace("-", "_") : ed.en_US);
  }
  set locale(e) {
    e && se.setItem(jo, e);
  }
  get country() {
    return se.getItem(Qo) ?? void 0;
  }
  set country(e) {
    e && se.setItem(Qo, e);
  }
  get regionType() {
    return se.getItem(Jo) ?? vs.REGION_CHINA_ONLY;
  }
  set regionType(e) {
    se.setItem(Jo, e);
  }
  get specialAppKey() {
    return se.getItem(qo) || "";
  }
  set specialAppKey(e) {
    e && se.setItem(qo, e);
  }
  get specialAppSecret() {
    return se.getItem(el) || "";
  }
  set specialAppSecret(e) {
    e && se.setItem(el, e);
  }
  get specialDataCenterSchema() {
    return se.getItem(tl) || xt.HTTPS;
  }
  set specialDataCenterSchema(e) {
    se.setItem(tl, e);
  }
  get specialDataCenterDomain() {
    return se.getItem(il) || "";
  }
  set specialDataCenterDomain(e) {
    se.setItem(il, e);
  }
  get specialSignalingSchema() {
    return se.getItem(sl) || xt.WSS;
  }
  set specialSignalingSchema(e) {
    se.setItem(sl, e);
  }
  get specialSignalingDomain() {
    return se.getItem(rl) || "";
  }
  set specialSignalingDomain(e) {
    se.setItem(rl, e);
  }
  clear() {
    [
      Vo,
      Wo,
      Ho,
      Zo,
      $o,
      Ko,
      Xo,
      Yo,
      zo,
      jo,
      Qo,
      Jo,
      qo,
      el,
      tl,
      il,
      sl,
      rl
    ].forEach((e) => {
      se.removeItem(e);
    });
  }
}
const re = new n2();
function a2(r) {
  switch (r) {
    case ps.COMMON:
      return !!(re.appKey && re.appSecret);
    case ps.SPECIAL:
      return !!(re.specialAppKey && re.specialAppSecret);
    default:
      return !1;
  }
}
const Ph = "RTCX_REGION_ID_KEY", kh = "RTCX_GATEWAY_PROTOCOL_KEY", wh = "RTCX_GATEWAY_DOMAIN_KEY", Mh = "RTCX_STUN_KEY";
class yr {
  constructor(e, t, i) {
    y(this, "protocol");
    y(this, "domainChina");
    y(this, "domainAbroad");
    this.protocol = e, this.domainChina = t, this.domainAbroad = i;
  }
}
const o2 = {
  [hi.LOCAL]: new yr(xt.HTTPS, "dnms.urtps.cn", "dnms.urtps.cn"),
  [hi.TEST]: new yr(xt.HTTPS, "dev-dnms.iotrtc.cn", "dev-dnms.iotrtc.cn"),
  [hi.PROD]: new yr(xt.HTTPS, "dnms.iotrtc.cn", "dnms.iotrtcx.com")
}, l2 = {
  [hi.LOCAL]: new yr(xt.WS, "dev-sig.iotrtc.cn", "dev-sig.iotrtc.cn"),
  [hi.TEST]: new yr(xt.WS, "dev-sig.iotrtc.cn", "dev-sig.iotrtc.cn"),
  [hi.PROD]: new yr(xt.WSS, "sig.iotrtc.cn:9824", "sig.iotrtcus.com:9824")
};
class c2 {
  get regionId() {
    return se.getItem(Ph) ?? -1;
  }
  set regionId(e) {
    se.setItem(Ph, e);
  }
  get gatewayProtocol() {
    return se.getItem(kh) ?? xt.HTTPS;
  }
  set gatewayProtocol(e) {
    se.setItem(kh, e);
  }
  get gatewayDomain() {
    return se.getItem(wh) ?? "gateway.iotrtc.cn";
  }
  set gatewayDomain(e) {
    se.setItem(wh, e);
  }
  get stunAddress() {
    return se.getItem(Mh) ?? "";
  }
  set stunAddress(e) {
    se.setItem(Mh, e);
  }
}
const Je = new c2(), nl = "RTCX_TOKEN_KEY", al = "RTCX_USER_ID_KEY", Fn = "TOKEN_EXPIRE_TIME_KEY", wi = {
  setUserToken(r) {
    se.setItem(nl, r);
  },
  getUserToken() {
    const r = se.getItem(nl), e = se.getItem(Fn);
    return !r || e < Date.now() ? "" : r;
  },
  setUserId(r) {
    return se.setItem(al, r);
  },
  getUserId() {
    return se.getItem(al) ?? 0;
  },
  setTokenExpiredTime(r) {
    return se.setItem(Fn, r);
  },
  getTokenExpiredTime() {
    return se.getItem(Fn) ?? -1;
  },
  clear() {
    se.removeItem(nl), se.removeItem(al), se.removeItem(Fn);
  }
}, ut = [];
for (let r = 0; r < 256; ++r)
  ut.push((r + 256).toString(16).slice(1));
function d2(r, e = 0) {
  return (ut[r[e + 0]] + ut[r[e + 1]] + ut[r[e + 2]] + ut[r[e + 3]] + "-" + ut[r[e + 4]] + ut[r[e + 5]] + "-" + ut[r[e + 6]] + ut[r[e + 7]] + "-" + ut[r[e + 8]] + ut[r[e + 9]] + "-" + ut[r[e + 10]] + ut[r[e + 11]] + ut[r[e + 12]] + ut[r[e + 13]] + ut[r[e + 14]] + ut[r[e + 15]]).toLowerCase();
}
let ol;
const h2 = new Uint8Array(16);
function u2() {
  if (!ol) {
    if (typeof crypto > "u" || !crypto.getRandomValues)
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    ol = crypto.getRandomValues.bind(crypto);
  }
  return ol(h2);
}
const f2 = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Bh = { randomUUID: f2 };
function p2(r, e, t) {
  var s;
  if (Bh.randomUUID && !r)
    return Bh.randomUUID();
  r = r || {};
  const i = r.random ?? ((s = r.rng) == null ? void 0 : s.call(r)) ?? u2();
  if (i.length < 16)
    throw new Error("Random bytes length must be >= 16");
  return i[6] = i[6] & 15 | 64, i[8] = i[8] & 63 | 128, d2(i);
}
const Dm = "RTCX_GATEWAY_clientUniqueKey";
function id() {
  return p2().replace(/-/g, "");
}
function _o() {
  return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString();
}
function Pm(r) {
  se.setItem(Dm, r);
}
function Rn() {
  let r = se.getItem(Dm);
  return r || (r = id(), Pm(r)), r;
}
function km() {
  let r = Math.random().toString().substring(2) + Date.now();
  return self.BigInt && (r = self.BigInt(r).toString(36)), r;
}
const m2 = {
  debug: !1,
  automaticOpen: !0,
  reconnectInterval: 1e3,
  maxReconnectInterval: 3e4,
  reconnectDecay: 1.5,
  timeoutInterval: 2e3,
  maxReconnectAttempts: void 0
}, ls = class ls extends ve {
  constructor(t, i, s) {
    super();
    y(this, "TAG", "ReconnectingWebSocket");
    y(this, "url");
    y(this, "protocols");
    y(this, "options");
    y(this, "reconnectAttempts", 0);
    y(this, "readyState", WebSocket.CONNECTING);
    y(this, "ws", null);
    y(this, "isTimeoutClosing", !1);
    y(this, "isClosed", !1);
    y(this, "timeoutTimer");
    y(this, "isWebsocketConnected");
    this.options = m2, s && Object.assign(this.options, s), this.url = t, this.protocols = i, this.options.automaticOpen === !0 && this.open(!1);
  }
  set binaryType(t) {
    const i = this.ws;
    i && (i.binaryType = t);
  }
  debugLog(...t) {
    var s;
    const { debug: i } = this.options;
    if (i || ls.debugAll) {
      if ((s = t[0]) != null && s.includes('"token"')) return;
      S.d(this.TAG, ...t);
    }
  }
  open(t) {
    const i = this.url;
    let s = this.ws = new WebSocket(i, this.protocols || []);
    const { maxReconnectAttempts: n, timeoutInterval: a, reconnectInterval: o, reconnectDecay: c, maxReconnectInterval: l } = this.options;
    if (t) {
      if (n && this.reconnectAttempts > n)
        return;
    } else
      this.emit("connecting"), this.reconnectAttempts = 0;
    this.debugLog("attempt-connect " + i), this.timeoutTimer = setTimeout(() => {
      this.debugLog("connection-timeout " + i), this.isTimeoutClosing = !0, s == null || s.close(), this.isTimeoutClosing = !1;
    }, a), s.onopen = () => {
      clearTimeout(this.timeoutTimer), this.debugLog("onopen", i), this.readyState = WebSocket.OPEN, this.reconnectAttempts = 0, t = !1, this.emit("open", t);
    }, s.onclose = (d) => {
      if (clearTimeout(this.timeoutTimer), this.ws = s = null, this.isClosed)
        this.readyState = WebSocket.CLOSED, this.emit("close");
      else {
        this.readyState = WebSocket.CONNECTING, this.emit("connecting", d), !t && !this.isTimeoutClosing && (this.debugLog("onclose " + i), this.emit("close"));
        const h = o * Math.pow(c, this.reconnectAttempts);
        setTimeout(
          () => {
            this.reconnectAttempts++, this.open(!0);
          },
          h > l ? l : h
        );
      }
    }, s.onmessage = (d) => {
      this.debugLog(`onmessage  ${i}  ${d.data}`), this.emit("message", d);
    }, s.onerror = (d) => {
      this.debugLog("onerror", i, d), this.emit("error", d);
    };
  }
  send(t) {
    const i = this.ws;
    if (i)
      return this.debugLog(`send  ${this.url} ${t}`), i.send(t);
    throw "INVALID_STATE_ERR : Pausing to reconnect websocket";
  }
  close(t, i) {
    var s;
    typeof t > "u" && (t = 1e3), this.isClosed = !0, (s = this.ws) == null || s.close(t, i);
  }
  refresh() {
    var t;
    (t = this.ws) == null || t.close();
  }
};
y(ls, "debugAll", !1), y(ls, "CONNECTING", WebSocket.CONNECTING), y(ls, "OPEN", WebSocket.OPEN), y(ls, "CLOSING", WebSocket.CLOSING), y(ls, "CLOSED", WebSocket.CLOSED);
let Z0 = ls;
class g2 {
  constructor() {
    y(this, "TAG", "SignalingWebSocketManage");
    y(this, "wsMap", /* @__PURE__ */ new Map());
    y(this, "wsClearTimers", /* @__PURE__ */ new Map());
  }
  /**
   *
   * @param {*} url
   * @param {*} key
   * @param {*} obj
   * @returns
   */
  getInstance(e, t, i, s) {
    S.d(this.TAG, "getInstance", i), clearTimeout(this.wsClearTimers.get(t));
    let { ws: n, mapTo: a = [] } = this.wsMap.get(t) || {};
    if (!n) {
      const c = { debug: !0, timeoutInterval: 1e4 };
      n = new Z0(e, void 0, c), n.setMaxListeners(100), n.addListener("open", () => {
        var l;
        (l = a[0]) == null || l.onWebSocketOpen();
      }), s && (n.binaryType = s);
    }
    a.push(i);
    const o = { ws: n, mapTo: a };
    return this.wsMap.set(t, o), o;
  }
  /**
   *
   * @param {*} key
   * @param {*} obj
   * @returns
   */
  releaseInstance(e, t) {
    var a, o;
    let { ws: i, mapTo: s = [] } = this.wsMap.get(e) || {};
    if (!i) return;
    const n = s.findIndex((c) => c === t);
    n > -1 && s.splice(n, 1), s.length ? n === 0 && (S.i(this.TAG, "start pingInterval"), (o = (a = s[0]) == null ? void 0 : a.pingInterval) == null || o.call(a)) : this.wsClearTimers.set(
      e,
      setTimeout(() => {
        var c;
        (c = i.removeAllListeners) == null || c.call(i), i.close(), this.wsMap.delete(e);
      }, 1e3)
    );
  }
}
const Fh = new g2();
let _2 = 0;
var ns = /* @__PURE__ */ ((r) => (r[r.ROUTE_INNER = 0] = "ROUTE_INNER", r[r.ROUTE_C2S = 1] = "ROUTE_C2S", r[r.ROUTE_S2C = 2] = "ROUTE_S2C", r[r.ROUTE_C2C = 3] = "ROUTE_C2C", r))(ns || {}), Vi = /* @__PURE__ */ ((r) => (r[r.CMD_LoginReq = 5] = "CMD_LoginReq", r[r.CMD_LoginRsp = 6] = "CMD_LoginRsp", r[r.CMD_HeartbeatReq = 7] = "CMD_HeartbeatReq", r[r.CMD_HeartbeatRsp = 8] = "CMD_HeartbeatRsp", r[r.CMD_THING_SERVICE_INVOKE = 143] = "CMD_THING_SERVICE_INVOKE", r[r.CMD_THING_SERVICE_INVOKE_RELAY = 144] = "CMD_THING_SERVICE_INVOKE_RELAY", r[r.CMD_THING_MEDIA_GET = 161] = "CMD_THING_MEDIA_GET", r[r.CMD_THING_MEDIA_GET_REPLY = 162] = "CMD_THING_MEDIA_GET_REPLY", r[r.CMD_THING_TOPIC_REGISTER = 17] = "CMD_THING_TOPIC_REGISTER", r[r.CMD_THING_TOPIC_REGISTER_REPLY = 18] = "CMD_THING_TOPIC_REGISTER_REPLY", r[r.CMD_THING_TOPIC_UNREGISTER = 19] = "CMD_THING_TOPIC_UNREGISTER", r[r.CMD_THING_TOPIC_UNREGISTER_REPLY = 20] = "CMD_THING_TOPIC_UNREGISTER_REPLY", r[r.CMD_THING_PROPERTY_CHANGE = 105] = "CMD_THING_PROPERTY_CHANGE", r[r.CMD_THING_PROPERTY_CHANGE_REPLY = 106] = "CMD_THING_PROPERTY_CHANGE_REPLY", r[r.CMD_THING_STATUS_NOTIFY = 27] = "CMD_THING_STATUS_NOTIFY", r[r.CMD_THING_STATUS_NOTIFY_REPLY = 28] = "CMD_THING_STATUS_NOTIFY_REPLY", r[r.CMD_THING_DELETE_NOTIFY = 29] = "CMD_THING_DELETE_NOTIFY", r[r.CMD_THING_DELETE_NOTIFY_REPLY = 30] = "CMD_THING_DELETE_NOTIFY_REPLY", r))(Vi || {}), Bt = /* @__PURE__ */ ((r) => (r.CMD_Login = "client.auth.login", r.CMD_Heartbeat = "thing.heartbeat", r.CMD_THING_MEDIA_GET = "thing.media.get", r.CMD_THING_INVOKE_SERVICE = "thing.service", r.CMD_THING_TOPIC_REGISTER = "thing.topic.regist", r.CMD_THING_TOPIC_UNREGISTER = "thing.topic.unregist", r.CMD_THING_PROPERTY_CHANGE = "thing.event.property.notify", r.CMD_THING_STATUS_NOTIFY = "thing.status.notify", r.CMD_THING_DELETE_NOTIFY = "thing.delete.notify", r))(Bt || {});
function Qs() {
  return {
    seq: _2++,
    timestamp: Date.now()
  };
}
function y2(r, e, t) {
  return {
    dst: t,
    seq: r,
    src: wi.getUserId().toString(),
    needAck: !0,
    srcSession: e
  };
}
const x2 = function() {
  let r = new ArrayBuffer(2);
  return new DataView(r).setInt16(0, 256, !0), new Int16Array(r)[0] === 256;
}(), v2 = 4;
function ui(...r) {
  const e = r.length;
  if (e < 1) throw "concatTypedArray: empty array";
  if (e < 2) return r[0];
  const t = r.reduce((n, a) => (n += a.length, n), 0), i = new r[0].constructor(t);
  let s = 0;
  return r.forEach((n) => {
    i.set(n, s), s += n.length;
  }), i;
}
function E2(r, e, t) {
  const i = r.length, s = e.length, n = i - s;
  for (let a = t; a < n; ++a)
    if (e.every((c, l) => c === r[a + l])) return a;
  return -1;
}
function wm(r, e) {
  return e.every((t, i) => t === r[i]);
}
function ua(r) {
  let e = new DataView(new ArrayBuffer(v2));
  return e.setUint32(0, r.length, !x2), ui(new Uint8Array(e.buffer), r);
}
function Ks(r, e, t, i, s, n = 0) {
  const a = Rn();
  return e && (e.clientUniqueKey = a), {
    id: _o(),
    version: "1.0",
    sys: t,
    params: e ?? {},
    method: r,
    srcUniqueId: a,
    productKey: i,
    deviceName: s,
    lensId: n
  };
}
function S2(r) {
  const e = Bt.CMD_Login;
  return Ks(e, r, {
    ack: 1
  });
}
function T2(r) {
  const e = Bt.CMD_THING_MEDIA_GET;
  return Ks(e, r, void 0, r.productKey, r.deviceName);
}
function b2() {
  const r = Bt.CMD_Heartbeat;
  return Ks(r);
}
function A2(r, e, t = 0, i, s, n) {
  const a = `${Bt.CMD_THING_INVOKE_SERVICE}.${i}`;
  return Ks(a, s, {
    ack: n
  }, r, e, t);
}
function C2(r, e, t = 0, i) {
  const s = Bt.CMD_THING_TOPIC_REGISTER;
  return Ks(s, i, void 0, r, e, t);
}
function R2(r, e, t = 0, i) {
  const s = Bt.CMD_THING_TOPIC_UNREGISTER;
  return Ks(s, i, void 0, r, e, t);
}
const ri = {
  string2Unit8Array(r = "", e = !1) {
    const t = new TextEncoder();
    return e && (r = encodeURIComponent(r)), t.encode(r);
  },
  unit8Array2String(r, e = !1) {
    let i = new TextDecoder().decode(r);
    return e ? decodeURIComponent(i) : i;
  }
}, Mm = "rtcx", Bm = 30314, Xs = Mm + "-websdk", Ur = `${Xs}-wrapper`, fa = `${Xs}-video-wrapper`, Fm = `${Xs}-render-wrapper`;
var gs = /* @__PURE__ */ ((r) => (r.GATEWAY = "gateway", r.STUN = "stun", r.WEB_H5 = "webH5", r))(gs || {});
const On = {
  WEBRTC: "webrtc",
  HLS: "hls"
};
let pa;
function I2(r) {
  pa = r;
}
function sd(r) {
  pa == null || pa(r);
}
const L2 = 3e4, Nn = /* @__PURE__ */ new Map(), D2 = {
  appKey: "",
  token: "",
  userId: 0
}, P2 = "SignalingWebSocketProxyEvent", $0 = {};
function Om(r, e) {
  if (!e.length) return;
  const t = r.productKey + r.deviceName, i = e.map((s) => s.productKey + s.deviceName);
  $0[t] = i;
}
class Nm extends ve {
  constructor(t, i, s) {
    super();
    y(this, "TAG");
    y(this, "options");
    y(this, "messageQueue", []);
    y(this, "webSocketServer");
    y(this, "ws", null);
    y(this, "srcSession", "");
    y(this, "onSignalingMessageCallbacks", /* @__PURE__ */ new Map());
    y(this, "webSocketPingInterval");
    y(this, "wsKey", "");
    y(this, "isDestroyed", !1);
    y(this, "onWebSocketOpen", () => {
      S.i(this.TAG, "onWebSocketOpen"), this.doLoginSignaling(), this.pingInterval();
    });
    y(this, "onSignalingMessage", (t) => {
      const { data: i } = t;
      if (i instanceof ArrayBuffer)
        this.dispatchArrayBuffer(i);
      else if (i instanceof Blob) {
        let s = new FileReader();
        s.onload = () => {
          this.dispatchArrayBuffer(s.result);
        }, s.readAsArrayBuffer(i);
      } else {
        let s = {
          code: -1,
          msg: "Unsupported WebSocket message type: " + i.constructor.name
        };
        S.e(this.TAG, "_onSignalingMessage", s);
      }
    });
    y(this, "onWebSocketClose", () => {
      S.i(this.TAG, "onWebSocketClose "), this.ws && (this.ws.isWebsocketConnected = !1), clearInterval(this.webSocketPingInterval);
    });
    y(this, "onWebSocketError", () => {
      S.e(this.TAG, "onWebSocketError "), this.ws && (this.ws.isWebsocketConnected = !1), clearInterval(this.webSocketPingInterval);
    });
    this.TAG = S.traceTag("SignalingWebSocket", s), this.options = Object.assign({}, D2, t), this.messageQueue = [], this.webSocketServer = i, this.init();
  }
  destroy() {
    this.isDestroyed = !0, Nn.forEach(this.clearTimeoutFallback.bind(this)), clearInterval(this.webSocketPingInterval), this.removeAllListeners();
    let t = this.ws;
    t && (t.removeListener("error", this.onWebSocketError), t.removeListener("close", this.onWebSocketClose), t.removeListener("message", this.onSignalingMessage), t = this.ws = null, Fh.releaseInstance(this.wsKey, this)), this.messageQueue = [], this.onSignalingMessageCallbacks.clear();
  }
  init() {
    self.WebSocket || S.e(this.TAG, "您的设备不支持 webSocket!");
    const { token: t } = this.options, i = this.webSocketServer;
    this.wsKey = JSON.stringify([i, t]), S.d(this.TAG, "wsKey" + this.wsKey);
    const { ws: s } = Fh.getInstance(i, this.wsKey, this, "arraybuffer");
    this.ws = s, s.addListener("error", this.onWebSocketError), s.addListener("close", this.onWebSocketClose), s.addListener("message", this.onSignalingMessage);
  }
  pingInterval() {
    clearInterval(this.webSocketPingInterval), this.webSocketPingInterval = setInterval(() => {
      this.sendWebSocketPing();
    }, 1e4);
  }
  doLoginSignaling() {
    const { appKey: t, userId: i, token: s } = this.options, n = Qs(), a = S2({
      appKey: t,
      userId: i,
      iotToken: s,
      clientUniqueKey: Rn()
    });
    this.realSendWebSocketMsg({
      arraybuffer: ri.string2Unit8Array(JSON.stringify(a), !1),
      routeId: ns.ROUTE_C2S,
      cmdId: Vi.CMD_LoginReq,
      seq: n.seq
    });
  }
  dispatchArrayBuffer(t) {
    const i = new DataView(t), s = new Uint8Array(t), n = i.getUint16(0, !1), a = i.getUint8(2), o = i.getUint16(3, !1), c = i.getUint32(5), l = n - 9;
    let d = 9, h = d + l;
    const u = s.slice(d, h);
    d = h, h = d + c;
    const f = s.slice(d, h), p = ri.unit8Array2String(u, !1);
    let m = ri.unit8Array2String(f, !1), g;
    try {
      g = JSON.parse(m);
    } catch (x) {
      S.e(this.TAG, "parse message data failed", x), m = m.replace(/\\x/g, ""), g = JSON.parse(m);
    }
    switch (S.v(this.TAG, `received signaling msg routeId =${a} cmdId=${o} routeExt=`, p, g), o) {
      case Vi.CMD_LoginRsp:
        this.srcSession = JSON.parse(p).dstSession, this.onLoginResp(g);
        break;
      case Vi.CMD_HeartbeatRsp:
        S.d(this.TAG, "received im pong msg");
        break;
      default: {
        const x = g.id;
        this.clearTimeoutFallback(x);
        const _ = this.onSignalingMessageCallbacks.get(x);
        if (_) {
          const { resolve: v } = _;
          v(g), this.onSignalingMessageCallbacks.delete(x);
        } else this.eventNames().find((v) => v === g.method) && this.emit(g.method, g);
        break;
      }
    }
  }
  onLoginResp(t) {
    const { code: i } = t;
    i === 200 ? (this.ws && (this.ws.isWebsocketConnected = !0), this.processMessageQueue()) : (S.e(this.TAG, "signaling login failed ", i), i === Bm && sd(new go("token invalid")));
  }
  processMessageQueue() {
    var t;
    if ((t = this.ws) != null && t.isWebsocketConnected)
      for (; this.messageQueue.length; ) {
        let i = this.messageQueue.shift();
        i && this.realSendWebSocketMsg(i);
      }
  }
  /**
   * 信令 buffer
   * @param {*} arraybuffer
   * @param {*} routeId
   * @param {*} cmdId
   * @param {*} seq
   * @returns
   */
  getSignalingSendBuffer(t, i, s, n, a, o) {
    S.d(this.TAG, `get signaling send msg routeId =${i} cmdId=${s} seq=${n} dst=${o} `);
    const c = new Uint8Array(9), l = new DataView(c.buffer), d = y2(n, a, o), h = ri.string2Unit8Array(JSON.stringify(d), !1), u = h.length;
    l.setUint16(0, u + 9, !1), l.setUint8(2, i), l.setUint16(3, s, !1);
    const f = t.length;
    return l.setUint32(5, f, !1), ui(c, h, t).buffer;
  }
  /**
   * 非arraybuffer 需要JSON序列号
   * @param {*} message
   */
  realSendWebSocketMsg(t) {
    var n;
    let i = t.dst;
    if (i) {
      const a = Object.keys($0).find((o) => {
        var c;
        return (c = $0[o]) == null ? void 0 : c.includes(i);
      });
      a && (i = a);
    }
    const s = this.getSignalingSendBuffer(t.arraybuffer, t.routeId, t.cmdId, t.seq, this.srcSession, i);
    try {
      (n = this.ws) == null || n.send(s);
    } catch {
      S.e(this.TAG, "relay webSocket handle exception");
    }
  }
  doWebSocketSend(t) {
    var s;
    const i = (s = this.ws) == null ? void 0 : s.isWebsocketConnected;
    i ? this.realSendWebSocketMsg(t) : (this.messageQueue.push(t), i !== void 0 ? S.e(this.TAG, "webSocket is lost connection", this.ws) : S.w(this.TAG, "waiting for websocket connection!", this.ws));
  }
  sendWebSocketPing() {
    const t = Qs(), i = b2();
    this.doWebSocketSend({
      arraybuffer: ri.string2Unit8Array(JSON.stringify(i), !1),
      routeId: ns.ROUTE_C2S,
      cmdId: Vi.CMD_HeartbeatReq,
      seq: t.seq
    });
  }
  setTimeoutFallback(t, i, s) {
    Nn.set(t, setTimeout(i, s || L2));
  }
  clearTimeoutFallback(t) {
    clearTimeout(Nn.get(t)), Nn.delete(t);
  }
  doSendSignalingCmd(t, i, s = Ke.NO_ACK, n) {
    return this.doWebSocketSend(i), s === Ke.NO_ACK ? Promise.resolve() : new Promise((a, o) => {
      this.setTimeoutFallback(
        t.id,
        () => {
          this.clearTimeoutFallback(t.id), a({
            code: -1,
            data: { msgId: t.id },
            method: t.method,
            message: "doSendSignalingCmd timeout",
            version: "1.0"
          });
        },
        n
      ), this.onSignalingMessageCallbacks.set(t.id, { resolve: a, reject: o });
    });
  }
  async thingMediaGet(t) {
    const i = Qs(), s = T2({
      ...t,
      initiator: "client"
    }), n = JSON.stringify(s);
    return S.d(this.TAG, "thingMediaGet", n), await this.doSendSignalingCmd(
      s,
      {
        arraybuffer: ri.string2Unit8Array(n, !1),
        routeId: ns.ROUTE_C2S,
        cmdId: Vi.CMD_THING_MEDIA_GET,
        seq: i.seq,
        dst: t.productKey + t.deviceName
      },
      1
    );
  }
  async invokeThingService(t) {
    const { productKey: i, deviceName: s, lensId: n = 0, identifier: a, params: o, ack: c = Ke.NO_ACK, timeout: l } = t, d = Qs(), h = A2(i, s, n, a, o, c), u = JSON.stringify(h);
    return S.d(this.TAG, "invokeThingService", u), await this.doSendSignalingCmd(
      h,
      {
        arraybuffer: ri.string2Unit8Array(u, !1),
        routeId: ns.ROUTE_C2C,
        cmdId: Vi.CMD_THING_SERVICE_INVOKE,
        seq: d.seq,
        dst: i + s
      },
      c,
      l
    );
  }
  async registerTopic(t, i, s, n) {
    S.d(this.TAG, "registerTopic", i);
    const a = Qs(), o = C2(t, i, s, n), c = JSON.stringify(o);
    return await this.doSendSignalingCmd(
      o,
      {
        arraybuffer: ri.string2Unit8Array(c, !1),
        routeId: ns.ROUTE_C2S,
        cmdId: Vi.CMD_THING_TOPIC_REGISTER,
        seq: a.seq,
        dst: t + i
      },
      Ke.NO_ACK
    );
  }
  async unregisterTopic(t, i, s, n) {
    S.d(this.TAG, "unregisterTopic", i);
    const a = Qs(), o = R2(t, i, s, n), c = JSON.stringify(o);
    return await this.doSendSignalingCmd(
      o,
      {
        arraybuffer: ri.string2Unit8Array(c, !1),
        routeId: ns.ROUTE_C2S,
        cmdId: Vi.CMD_THING_TOPIC_UNREGISTER,
        seq: a.seq,
        dst: t + i
      },
      Ke.NO_ACK
    );
  }
}
y(Nm, "ProxyEventName", P2);
let ds;
function k2() {
  if (re.signalingDomain)
    return re.signalingSchema + "://" + re.signalingDomain;
  const r = l2[re.platformEnv], e = re.regionType == vs.REGION_ALL ? r.domainAbroad : r.domainChina;
  return r.protocol + "://" + e;
}
function Ii(r = km()) {
  return (!ds || ds.isDestroyed) && (ds = new Nm(
    {
      appKey: re.appKey,
      token: wi.getUserToken(),
      userId: wi.getUserId()
    },
    k2(),
    r
  )), ds;
}
function Gm() {
  ds == null || ds.destroy(), ds = null;
}
class w2 {
  constructor() {
    y(this, "TAG", "SDCardService");
  }
  /**
   * 按时间段获取SD卡录制文件
   *
   * @param params - 请求参数
   * @public
   */
  async recordTimeQuery(e) {
    var o;
    const t = e.pageSize, i = e.beginTime;
    let s = e.endTime;
    const n = {
      recordFileList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let a;
    do {
      const c = {
        BeginTime: i.toString(),
        EndTime: s.toString(),
        QuerySize: Math.min(t - n.recordFileList.length, 30),
        Type: e.recordType ?? 99
      }, l = {
        productKey: e.productKey,
        deviceName: e.deviceName,
        identifier: rt.QueryRecordTimeList,
        params: c,
        ack: Ke.NEED_ACK
      }, d = await Ii().invokeThingService(l);
      if (S.v(this.TAG, d), !d) break;
      const h = d.data;
      if (!(h != null && h.TimeList) || (n.nextValid = h.NextValid == 1, a = h.TimeList.sort((f, p) => Number(p.BeginTime) - Number(f.BeginTime)), !a.length)) break;
      const u = a.map((f) => ({
        beginTime: Number(f.BeginTime),
        endTime: Number(f.EndTime),
        recordType: Number(f.Type)
      }));
      if (n.nextEndTime = (o = u.at(-1)) == null ? void 0 : o.beginTime, n.recordFileList.push(...u), n.recordFileList.length >= t || h.NextValid == 0) break;
      s = n.nextEndTime, s > 0 && s--;
    } while (i < s);
    if ((n.nextEndTime == null || !n.nextValid && n.nextEndTime >= i) && (n.nextEndTime = i), !n.recordFileList.length && a == null)
      throw "sdcard timeline time record  response error";
    return n;
  }
  /**
   * 按文件获取SD卡录制文件
   *
   * @param params - 请求参数 [SDCardRecordQueryReq]
   */
  async recordFileQuery(e) {
    var o;
    const t = e.pageSize, i = e.beginTime;
    let s = e.endTime;
    const n = {
      recordFileList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let a;
    do {
      const c = {
        BeginTime: i.toString(),
        EndTime: s.toString(),
        QuerySize: Math.min(t - n.recordFileList.length, 30),
        Type: e.recordType
      }, l = {
        productKey: e.productKey,
        deviceName: e.deviceName,
        identifier: rt.QueryRecordList,
        params: c,
        ack: Ke.NEED_ACK
      }, d = await Ii().invokeThingService(l);
      if (!d) break;
      const h = d.data;
      if ((h == null ? void 0 : h.RecordList) == null || (n.nextValid = h.NextValid == 1, a = h.RecordList.sort((f, p) => Number(p.BeginTime) - Number(f.BeginTime)), !a.length)) break;
      const u = a.map((f) => ({
        filename: f.FileName,
        fileSize: f.Size,
        recordType: Number(f.Type),
        beginTime: Number(f.BeginTime),
        endTime: Number(f.EndTime)
      }));
      if (n.nextEndTime = (o = u.at(-1)) == null ? void 0 : o.beginTime, n.recordFileList.push(...u), n.recordFileList.length >= t || h.NextValid == 0) break;
      s = n.nextEndTime, s > 0 && s--;
    } while (i < s);
    if ((n.nextEndTime == null || !n.nextValid && n.nextEndTime >= i) && (n.nextEndTime = i), !n.recordFileList.length && a == null)
      throw "sdcard timeline file record response error";
    return n;
  }
  /**
   * 按时间段获取事件文件
   *
   * @param params - 请求参数 [SDCardEventQueryReq]
   */
  async eventTimeQuery(e) {
    var o;
    const t = e.pageSize, i = e.beginTime;
    let s = e.endTime;
    const n = {
      eventList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let a;
    do {
      const c = {
        BeginTime: i.toString(),
        EndTime: s.toString(),
        QuerySize: Math.min(t - n.eventList.length, 50)
      };
      e.eventType || (c.Type = e.eventType);
      const l = {
        productKey: e.productKey,
        deviceName: e.deviceName,
        identifier: rt.QueryEventTimeList,
        params: c,
        ack: Ke.NEED_ACK
      }, d = await Ii().invokeThingService(l);
      if (!d) break;
      const h = d.data;
      if ((h == null ? void 0 : h.TimeList) == null || (n.nextValid = h.NextValid == 1, a = h.TimeList.sort((f, p) => Number(p.BeginTime) - Number(f.BeginTime)), !a.length)) break;
      const u = a.map((f) => ({
        beginTime: Number(f.BeginTime),
        endTime: Number(f.EndTime),
        eventType: Number(f.Type),
        eventId: Number(f.BeginTime),
        picId: f.PicId
      }));
      if (n.nextEndTime = (o = u.at(-1)) == null ? void 0 : o.beginTime, n.eventList.push(...u), n.eventList.length >= t || h.NextValid == 0) break;
      s = n.nextEndTime, s > 0 && s--;
    } while (i < s);
    if ((n.nextEndTime == null || !n.nextValid && n.nextEndTime >= i) && (n.nextEndTime = i), !n.eventList.length && a == null)
      throw "sdcard timeline time event response error";
    return n;
  }
  /**
   * 按月查询录制统计
   *
   * @param monthQueryReq - [SDCardRecordMonthQueryReq]
   */
  async monthRecordQuery(e) {
    var o;
    const t = {
      Year: e.year,
      Month: e.month
    }, i = {
      productKey: e.productKey,
      deviceName: e.deviceName,
      identifier: rt.QueryMonthRecord,
      params: t,
      ack: Ke.NEED_ACK
    }, s = await Ii().invokeThingService(i);
    if (!s) throw "sdcard monthRecordQuery error";
    const n = s.data, a = [];
    return (o = n == null ? void 0 : n.MonthRecordList) == null || o.forEach((c) => {
      c && a.push({ dateStr: c.DateStr, count: 1 });
    }), { dayCntList: a };
  }
}
const d6 = new w2();
var He = /* @__PURE__ */ ((r) => (r.DeviceSdkAbility = "deviceSdkAbility", r.CapsList = "CapsList", r.LensCount = "LensCount", r.CodecList = "CodecList", r.VideoCodec = "VideoCodec", r.AudioCodec = "AudioCodec", r.SubVideoCodec = "SubVideoCodec", r.SubAudioCodec = "SubAudioCodec", r.TalkAudioCodec = "TalkAudioCodec", r.powerstate = "powerstate", r.DeviceWorkMode = "DeviceWorkMode", r))(He || {}), Um = /* @__PURE__ */ ((r) => (r.StartPTZAction = "StartPTZAction", r.StopPTZAction = "StopPTZAction", r.PTZActionControl = "PTZActionControl", r.PTZReset = "PTZReset", r.GetPTZPosition = "GetPTZPosition", r.PTZMove = "PTZMove", r.devTransMsg = "devTransMsg", r))(Um || {}), Ir = /* @__PURE__ */ ((r) => (r[r.SDK_ABILITY_RTC_P2P = 1] = "SDK_ABILITY_RTC_P2P", r[r.SDK_ABILITY_RTC_CMS = 2] = "SDK_ABILITY_RTC_CMS", r[r.SDK_ABILITY_RTMP_PUSH = 3] = "SDK_ABILITY_RTMP_PUSH", r[r.SDK_ABILITY_DIRECT_STORAGE = 4] = "SDK_ABILITY_DIRECT_STORAGE", r[r.SDK_ABILITY_SCHEDULE_RECORD = 5] = "SDK_ABILITY_SCHEDULE_RECORD", r[r.SDK_ABILITY_SCHEDULE_POWER_OFF = 6] = "SDK_ABILITY_SCHEDULE_POWER_OFF", r[r.SDK_ABILITY_COMPRESS_DATA = 7] = "SDK_ABILITY_COMPRESS_DATA", r[r.SDK_ABILITY_SUPPORT_DIAN_YUN = 8] = "SDK_ABILITY_SUPPORT_DIAN_YUN", r[r.SDK_ABILITY_DATA_CHANNEL = 9] = "SDK_ABILITY_DATA_CHANNEL", r[r.SDK_ABILITY_P2P_SEND_AUDIO = 10] = "SDK_ABILITY_P2P_SEND_AUDIO", r))(Ir || {}), hs = /* @__PURE__ */ ((r) => (r.DEVICE_UNBIND = "DEVICE_UNBIND", r.DEVICE_STATUS = "DEVICE_STATUS", r.DEVICE_THING_PROPERTIES_CHANGE = "DEVICE_THING_PROPERTIES_CHANGE", r.DEV_TRANS_MSG = "DEV_TRANS_MSG", r))(hs || {});
const h6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  SubscribeEventTypeEnum: hs,
  ThingSDKAbilityEnum: Ir
}, Symbol.toStringTag, { value: "Module" }));
var Vm = /* @__PURE__ */ ((r) => (r[r.SHARED = 0] = "SHARED", r[r.OWNED = 1] = "OWNED", r))(Vm || {}), Wm = /* @__PURE__ */ ((r) => (r.DEVICE = "DEVICE", r))(Wm || {}), rd = /* @__PURE__ */ ((r) => (r.DEVICE = "DEVICE", r.GATEWAY = "GATEWAY", r))(rd || {}), Hm = /* @__PURE__ */ ((r) => (r.XS_IOT_WORK_MODE_LOWPOWER_PROXY = "1", r.XS_IOT_WORK_MODE_LONG_TIME_POWER = "2", r.XS_IOT_WORK_MODE_LOWPOWER_SEPARATE = "3", r.XS_IOT_WORK_MODE_LOWPOWER_KEEPLIVE = "4", r))(Hm || {}), yo = /* @__PURE__ */ ((r) => (r[r.UNKNOWN = -1] = "UNKNOWN", r[r.NOT_ACTIVE = 0] = "NOT_ACTIVE", r[r.ONLINE = 1] = "ONLINE", r[r.SLEEP = 2] = "SLEEP", r[r.OFFLINE = 3] = "OFFLINE", r[r.DISABLE = 8] = "DISABLE", r))(yo || {});
class M2 {
  constructor(e, t, i) {
    y(this, "iotId");
    y(this, "productKey");
    y(this, "deviceName");
    this.iotId = e, this.productKey = t, this.deviceName = i;
  }
}
class xo {
  constructor(e, t) {
    /**
     * 设备是通用版，还是专属版
     * @internal
     */
    y(this, "platformType", ps.COMMON);
    /**
     * 局域网设备信令地址
     * @internal
     */
    y(this, "lanSignalAddressInfo");
    /**
     * 物模型属性，不要操作
     * @internal
     */
    y(this, "thingProperties", {});
    y(this, "iotId");
    y(this, "productKey");
    y(this, "deviceName");
    y(this, "status", 1);
    y(this, "owned", 1);
    y(this, "gmtModified", 0);
    y(this, "region");
    y(this, "identityId");
    y(this, "productName");
    y(this, "productModel");
    y(this, "nickName");
    y(this, "netType");
    y(this, "groupId");
    y(this, "sharePermissionList");
    y(this, "thingType", "DEVICE");
    y(this, "nodeType", "DEVICE");
    y(this, "parentNodeType", "DEVICE");
    /**
     * 设备缩略图
     * @public
     */
    y(this, "thumbnail");
    /**
     * 镜头ID 多目设备使用
     * @public
     */
    y(this, "lensId");
    this.iotId = e.iotId, this.productKey = e.productKey, this.deviceName = e.deviceName, this.status = e.status ?? -1, this.owned = e.owned ?? 1, this.gmtModified = e.gmtModified ?? 0, this.region = e.region, this.identityId = e.identityId, this.productName = e.productName, this.productModel = e.productModel, this.nickName = e.nickName, this.netType = e.netType, this.groupId = e.groupId, this.sharePermissionList = e.sharePermissionList, this.thingType = e.thingType ?? "DEVICE", this.nodeType = e.nodeType ?? "DEVICE", this.parentNodeType = e.parentNodeType ?? "DEVICE", t && (this.platformType = t);
  }
  /**
   * 获取设备显示文案（优先别名）
   * @returns
   */
  getShowName() {
    return this.nickName || this.deviceName;
  }
  /**
   * 设备镜头数
   */
  get lensCount() {
    return Number(this.thingProperties[He.LensCount] || 1);
  }
  /**
   * 设备是否支持P2P
   */
  get isSupportP2P() {
    return this.supportSdkAbility(Ir.SDK_ABILITY_RTC_P2P);
  }
  /**
   * 设备是否支持信令压缩数据
   */
  get isSupportCompressData() {
    return this.supportSdkAbility(Ir.SDK_ABILITY_COMPRESS_DATA);
  }
  /**
   * 设备工作模式
   */
  get deviceWorkMode() {
    return this.thingProperties[He.DeviceWorkMode] ?? "2";
  }
  /**
   * 设备所在平台类型
   * @internal
   */
  get cloudPlatformTypeEnum() {
    return this.platformType;
  }
  set cloudPlatformTypeEnum(e) {
    this.platformType = e;
  }
  /**
   * 设备SDK支持能力
   */
  supportSdkAbility(e) {
    const t = this.thingProperties[He.DeviceSdkAbility];
    return t ? JSON.parse(t).includes(e) : !1;
  }
  /**
   * 是否是专属版设备
   *
   * @returns
   */
  isSpecialDevice() {
    return this.platformType == ps.SPECIAL;
  }
  /**
   * 是否是局域网设备
   *
   * @returns
   */
  isLanDevice() {
    return this.platformType == ps.LAN;
  }
}
var ms = /* @__PURE__ */ ((r) => (r[r.LIVE_PLAY_STRATEGY = 1e3] = "LIVE_PLAY_STRATEGY", r[r.MSG_PUSH_SETTING = 1003] = "MSG_PUSH_SETTING", r[r.PTZ_PRESET_LIST = 1004] = "PTZ_PRESET_LIST", r[r.LIVE_PLAY_DURATION_LIMIT = 1008] = "LIVE_PLAY_DURATION_LIMIT", r))(ms || {}), en = /* @__PURE__ */ ((r) => (r[r.DEVICE = 0] = "DEVICE", r[r.USER = 2] = "USER", r))(en || {}), Zm = /* @__PURE__ */ ((r) => (r[r.INIT = -1] = "INIT", r[r.ACCEPTED = 0] = "ACCEPTED", r[r.REFUSED = 1] = "REFUSED", r[r.CANCELED = 2] = "CANCELED", r[r.EXPIRED = 3] = "EXPIRED", r[r.GRABED = 4] = "GRABED", r[r.DELETED = 5] = "DELETED", r[r.UNBIND = 6] = "UNBIND", r[r.ERROR = 99] = "ERROR", r))(Zm || {}), $m = /* @__PURE__ */ ((r) => (r.live = "live", r.record = "record", r.ptz = "ptz", r.voiceIntercom = "voiceIntercom", r.notification = "notification", r))($m || {}), Km = /* @__PURE__ */ ((r) => (r.MOBILE = "MOBILE", r.EMAIL = "EMAIL", r))(Km || {});
const u6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  DeviceEntityDimensionEnum: en,
  DeviceEntityEnum: ms,
  DeviceNodeTypeEnum: rd,
  DeviceOwnTypeEnum: Vm,
  DeviceSharedStatusEnum: Zm,
  DeviceStatusEnum: yo,
  DeviceThingTypeEnum: Wm,
  DeviceWorkModeEnum: Hm,
  PlayDeviceInfo: xo,
  SampleDeviceInfo: M2,
  ShareAccountAttrTypeEnum: Km,
  ShareDevicePermissionEnum: $m
}, Symbol.toStringTag, { value: "Module" }));
var vt = /* @__PURE__ */ ((r) => (r.LIST_BINDING_BY_ACCOUNT = "/client/uc/listBindingByAccount", r.UNBIND_ACCOUNT_AND_DEV = "/client/uc/unbindAccountAndDev", r.SUB_DEVICE_LIST = "/client/subdevices/list", r.DEVICE_WAKE_UP = "/client/device/wakeup", r.SET_DEVICE_NICK_NAME = "/client/uc/setDeviceNickName", r.GENERATE_SHARE_QRCODE = "/client/uc/generateShareQrCode", r.SCAN_BIND_BY_SHARE_QRCODE = "/client/uc/scanBindByShareQrCode", r.SHARE_DEVICE_TO_USER = "/client/uc/shareDevices", r.OWNER_CANCEL_SHARE = "/client/uc/cancelShare", r.CONFIRM_SHARE = "/client/uc/confirmShare", r.GET_SHARE_NOTICE_LIST = "/client/uc/getShareNoticeList", r.QUERY_SHARE_RECORD_BY_BATCH = "/client/living/user/device/shared/record/query", r.SHARE_PERMISSION_SET = "/client/user/share/setPermissionList", r.GET_SHARED_USERS = "/client/living/user/device/shared/list", r.GET_SHARED_COUNT = "/client/living/user/device/share/count", r))(vt || {}), Ua = { exports: {} };
/*! https://mths.be/punycode v1.4.1 by @mathias */
Ua.exports;
(function(r, e) {
  (function(t) {
    var i = e && !e.nodeType && e, s = r && !r.nodeType && r, n = typeof le == "object" && le;
    (n.global === n || n.window === n || n.self === n) && (t = n);
    var a, o = 2147483647, c = 36, l = 1, d = 26, h = 38, u = 700, f = 72, p = 128, m = "-", g = /^xn--/, x = /[^\x20-\x7E]/, _ = /[\x2E\u3002\uFF0E\uFF61]/g, v = {
      overflow: "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    }, E = c - l, b = Math.floor, A = String.fromCharCode, C;
    function I(W) {
      throw new RangeError(v[W]);
    }
    function L(W, k) {
      for (var P = W.length, B = []; P--; )
        B[P] = k(W[P]);
      return B;
    }
    function R(W, k) {
      var P = W.split("@"), B = "";
      P.length > 1 && (B = P[0] + "@", W = P[1]), W = W.replace(_, ".");
      var O = W.split("."), j = L(O, k).join(".");
      return B + j;
    }
    function D(W) {
      for (var k = [], P = 0, B = W.length, O, j; P < B; )
        O = W.charCodeAt(P++), O >= 55296 && O <= 56319 && P < B ? (j = W.charCodeAt(P++), (j & 64512) == 56320 ? k.push(((O & 1023) << 10) + (j & 1023) + 65536) : (k.push(O), P--)) : k.push(O);
      return k;
    }
    function M(W) {
      return L(W, function(k) {
        var P = "";
        return k > 65535 && (k -= 65536, P += A(k >>> 10 & 1023 | 55296), k = 56320 | k & 1023), P += A(k), P;
      }).join("");
    }
    function w(W) {
      return W - 48 < 10 ? W - 22 : W - 65 < 26 ? W - 65 : W - 97 < 26 ? W - 97 : c;
    }
    function N(W, k) {
      return W + 22 + 75 * (W < 26) - ((k != 0) << 5);
    }
    function H(W, k, P) {
      var B = 0;
      for (W = P ? b(W / u) : W >> 1, W += b(W / k); W > E * d >> 1; B += c)
        W = b(W / E);
      return b(B + (E + 1) * W / (W + h));
    }
    function G(W) {
      var k = [], P = W.length, B, O = 0, j = p, Q = f, ne, J, Se, Ce, Te, Xe, be, Re, mt;
      for (ne = W.lastIndexOf(m), ne < 0 && (ne = 0), J = 0; J < ne; ++J)
        W.charCodeAt(J) >= 128 && I("not-basic"), k.push(W.charCodeAt(J));
      for (Se = ne > 0 ? ne + 1 : 0; Se < P; ) {
        for (Ce = O, Te = 1, Xe = c; Se >= P && I("invalid-input"), be = w(W.charCodeAt(Se++)), (be >= c || be > b((o - O) / Te)) && I("overflow"), O += be * Te, Re = Xe <= Q ? l : Xe >= Q + d ? d : Xe - Q, !(be < Re); Xe += c)
          mt = c - Re, Te > b(o / mt) && I("overflow"), Te *= mt;
        B = k.length + 1, Q = H(O - Ce, B, Ce == 0), b(O / B) > o - j && I("overflow"), j += b(O / B), O %= B, k.splice(O++, 0, j);
      }
      return M(k);
    }
    function Z(W) {
      var k, P, B, O, j, Q, ne, J, Se, Ce, Te, Xe = [], be, Re, mt, ee;
      for (W = D(W), be = W.length, k = p, P = 0, j = f, Q = 0; Q < be; ++Q)
        Te = W[Q], Te < 128 && Xe.push(A(Te));
      for (B = O = Xe.length, O && Xe.push(m); B < be; ) {
        for (ne = o, Q = 0; Q < be; ++Q)
          Te = W[Q], Te >= k && Te < ne && (ne = Te);
        for (Re = B + 1, ne - k > b((o - P) / Re) && I("overflow"), P += (ne - k) * Re, k = ne, Q = 0; Q < be; ++Q)
          if (Te = W[Q], Te < k && ++P > o && I("overflow"), Te == k) {
            for (J = P, Se = c; Ce = Se <= j ? l : Se >= j + d ? d : Se - j, !(J < Ce); Se += c)
              ee = J - Ce, mt = c - Ce, Xe.push(
                A(N(Ce + ee % mt, 0))
              ), J = b(ee / mt);
            Xe.push(A(N(J, 0))), j = H(P, Re, B == O), P = 0, ++B;
          }
        ++P, ++k;
      }
      return Xe.join("");
    }
    function $(W) {
      return R(W, function(k) {
        return g.test(k) ? G(k.slice(4).toLowerCase()) : k;
      });
    }
    function Y(W) {
      return R(W, function(k) {
        return x.test(k) ? "xn--" + Z(k) : k;
      });
    }
    if (a = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      version: "1.4.1",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      ucs2: {
        decode: D,
        encode: M
      },
      decode: G,
      encode: Z,
      toASCII: Y,
      toUnicode: $
    }, i && s)
      if (r.exports == i)
        s.exports = a;
      else
        for (C in a)
          a.hasOwnProperty(C) && (i[C] = a[C]);
    else
      t.punycode = a;
  })(le);
})(Ua, Ua.exports);
var B2 = Ua.exports, Or = TypeError, nd = typeof Map == "function" && Map.prototype, ll = Object.getOwnPropertyDescriptor && nd ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null, Va = nd && ll && typeof ll.get == "function" ? ll.get : null, Oh = nd && Map.prototype.forEach, ad = typeof Set == "function" && Set.prototype, cl = Object.getOwnPropertyDescriptor && ad ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null, Wa = ad && cl && typeof cl.get == "function" ? cl.get : null, Nh = ad && Set.prototype.forEach, F2 = typeof WeakMap == "function" && WeakMap.prototype, tn = F2 ? WeakMap.prototype.has : null, O2 = typeof WeakSet == "function" && WeakSet.prototype, sn = O2 ? WeakSet.prototype.has : null, N2 = typeof WeakRef == "function" && WeakRef.prototype, Gh = N2 ? WeakRef.prototype.deref : null, G2 = Boolean.prototype.valueOf, U2 = Object.prototype.toString, V2 = Function.prototype.toString, W2 = String.prototype.match, od = String.prototype.slice, us = String.prototype.replace, H2 = String.prototype.toUpperCase, Uh = String.prototype.toLowerCase, Xm = RegExp.prototype.test, Vh = Array.prototype.concat, bi = Array.prototype.join, Z2 = Array.prototype.slice, Wh = Math.floor, K0 = typeof BigInt == "function" ? BigInt.prototype.valueOf : null, dl = Object.getOwnPropertySymbols, X0 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? Symbol.prototype.toString : null, Lr = typeof Symbol == "function" && typeof Symbol.iterator == "object", rn = typeof Symbol == "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === Lr || !0) ? Symbol.toStringTag : null, Ym = Object.prototype.propertyIsEnumerable, Hh = (typeof Reflect == "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(r) {
  return r.__proto__;
} : null);
function Zh(r, e) {
  if (r === 1 / 0 || r === -1 / 0 || r !== r || r && r > -1e3 && r < 1e3 || Xm.call(/e/, e))
    return e;
  var t = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
  if (typeof r == "number") {
    var i = r < 0 ? -Wh(-r) : Wh(r);
    if (i !== r) {
      var s = String(i), n = od.call(e, s.length + 1);
      return us.call(s, t, "$&_") + "." + us.call(us.call(n, /([0-9]{3})/g, "$&_"), /_$/, "");
    }
  }
  return us.call(e, t, "$&_");
}
var Y0 = Rm, $h = Y0.custom, Kh = Qm($h) ? $h : null, zm = {
  __proto__: null,
  double: '"',
  single: "'"
}, $2 = {
  __proto__: null,
  double: /(["\\])/g,
  single: /(['\\])/g
}, vo = function r(e, t, i, s) {
  var n = t || {};
  if (Hi(n, "quoteStyle") && !Hi(zm, n.quoteStyle))
    throw new TypeError('option "quoteStyle" must be "single" or "double"');
  if (Hi(n, "maxStringLength") && (typeof n.maxStringLength == "number" ? n.maxStringLength < 0 && n.maxStringLength !== 1 / 0 : n.maxStringLength !== null))
    throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
  var a = Hi(n, "customInspect") ? n.customInspect : !0;
  if (typeof a != "boolean" && a !== "symbol")
    throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
  if (Hi(n, "indent") && n.indent !== null && n.indent !== "	" && !(parseInt(n.indent, 10) === n.indent && n.indent > 0))
    throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
  if (Hi(n, "numericSeparator") && typeof n.numericSeparator != "boolean")
    throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
  var o = n.numericSeparator;
  if (typeof e > "u")
    return "undefined";
  if (e === null)
    return "null";
  if (typeof e == "boolean")
    return e ? "true" : "false";
  if (typeof e == "string")
    return qm(e, n);
  if (typeof e == "number") {
    if (e === 0)
      return 1 / 0 / e > 0 ? "0" : "-0";
    var c = String(e);
    return o ? Zh(e, c) : c;
  }
  if (typeof e == "bigint") {
    var l = String(e) + "n";
    return o ? Zh(e, l) : l;
  }
  var d = typeof n.depth > "u" ? 5 : n.depth;
  if (typeof i > "u" && (i = 0), i >= d && d > 0 && typeof e == "object")
    return z0(e) ? "[Array]" : "[Object]";
  var h = cx(n, i);
  if (typeof s > "u")
    s = [];
  else if (Jm(s, e) >= 0)
    return "[Circular]";
  function u(w, N, H) {
    if (N && (s = Z2.call(s), s.push(N)), H) {
      var G = {
        depth: n.depth
      };
      return Hi(n, "quoteStyle") && (G.quoteStyle = n.quoteStyle), r(w, G, i + 1, s);
    }
    return r(w, n, i + 1, s);
  }
  if (typeof e == "function" && !Xh(e)) {
    var f = ex(e), p = Gn(e, u);
    return "[Function" + (f ? ": " + f : " (anonymous)") + "]" + (p.length > 0 ? " { " + bi.call(p, ", ") + " }" : "");
  }
  if (Qm(e)) {
    var m = Lr ? us.call(String(e), /^(Symbol\(.*\))_[^)]*$/, "$1") : X0.call(e);
    return typeof e == "object" && !Lr ? Vr(m) : m;
  }
  if (ax(e)) {
    for (var g = "<" + Uh.call(String(e.nodeName)), x = e.attributes || [], _ = 0; _ < x.length; _++)
      g += " " + x[_].name + "=" + jm(K2(x[_].value), "double", n);
    return g += ">", e.childNodes && e.childNodes.length && (g += "..."), g += "</" + Uh.call(String(e.nodeName)) + ">", g;
  }
  if (z0(e)) {
    if (e.length === 0)
      return "[]";
    var v = Gn(e, u);
    return h && !lx(v) ? "[" + j0(v, h) + "]" : "[ " + bi.call(v, ", ") + " ]";
  }
  if (Y2(e)) {
    var E = Gn(e, u);
    return !("cause" in Error.prototype) && "cause" in e && !Ym.call(e, "cause") ? "{ [" + String(e) + "] " + bi.call(Vh.call("[cause]: " + u(e.cause), E), ", ") + " }" : E.length === 0 ? "[" + String(e) + "]" : "{ [" + String(e) + "] " + bi.call(E, ", ") + " }";
  }
  if (typeof e == "object" && a) {
    if (Kh && typeof e[Kh] == "function" && Y0)
      return Y0(e, { depth: d - i });
    if (a !== "symbol" && typeof e.inspect == "function")
      return e.inspect();
  }
  if (tx(e)) {
    var b = [];
    return Oh && Oh.call(e, function(w, N) {
      b.push(u(N, e, !0) + " => " + u(w, e));
    }), Yh("Map", Va.call(e), b, h);
  }
  if (rx(e)) {
    var A = [];
    return Nh && Nh.call(e, function(w) {
      A.push(u(w, e));
    }), Yh("Set", Wa.call(e), A, h);
  }
  if (ix(e))
    return hl("WeakMap");
  if (nx(e))
    return hl("WeakSet");
  if (sx(e))
    return hl("WeakRef");
  if (j2(e))
    return Vr(u(Number(e)));
  if (J2(e))
    return Vr(u(K0.call(e)));
  if (Q2(e))
    return Vr(G2.call(e));
  if (z2(e))
    return Vr(u(String(e)));
  if (typeof window < "u" && e === window)
    return "{ [object Window] }";
  if (typeof globalThis < "u" && e === globalThis || typeof le < "u" && e === le)
    return "{ [object globalThis] }";
  if (!X2(e) && !Xh(e)) {
    var C = Gn(e, u), I = Hh ? Hh(e) === Object.prototype : e instanceof Object || e.constructor === Object, L = e instanceof Object ? "" : "null prototype", R = !I && rn && Object(e) === e && rn in e ? od.call(Ss(e), 8, -1) : L ? "Object" : "", D = I || typeof e.constructor != "function" ? "" : e.constructor.name ? e.constructor.name + " " : "", M = D + (R || L ? "[" + bi.call(Vh.call([], R || [], L || []), ": ") + "] " : "");
    return C.length === 0 ? M + "{}" : h ? M + "{" + j0(C, h) + "}" : M + "{ " + bi.call(C, ", ") + " }";
  }
  return String(e);
};
function jm(r, e, t) {
  var i = t.quoteStyle || e, s = zm[i];
  return s + r + s;
}
function K2(r) {
  return us.call(String(r), /"/g, "&quot;");
}
function Ys(r) {
  return !rn || !(typeof r == "object" && (rn in r || typeof r[rn] < "u"));
}
function z0(r) {
  return Ss(r) === "[object Array]" && Ys(r);
}
function X2(r) {
  return Ss(r) === "[object Date]" && Ys(r);
}
function Xh(r) {
  return Ss(r) === "[object RegExp]" && Ys(r);
}
function Y2(r) {
  return Ss(r) === "[object Error]" && Ys(r);
}
function z2(r) {
  return Ss(r) === "[object String]" && Ys(r);
}
function j2(r) {
  return Ss(r) === "[object Number]" && Ys(r);
}
function Q2(r) {
  return Ss(r) === "[object Boolean]" && Ys(r);
}
function Qm(r) {
  if (Lr)
    return r && typeof r == "object" && r instanceof Symbol;
  if (typeof r == "symbol")
    return !0;
  if (!r || typeof r != "object" || !X0)
    return !1;
  try {
    return X0.call(r), !0;
  } catch {
  }
  return !1;
}
function J2(r) {
  if (!r || typeof r != "object" || !K0)
    return !1;
  try {
    return K0.call(r), !0;
  } catch {
  }
  return !1;
}
var q2 = Object.prototype.hasOwnProperty || function(r) {
  return r in this;
};
function Hi(r, e) {
  return q2.call(r, e);
}
function Ss(r) {
  return U2.call(r);
}
function ex(r) {
  if (r.name)
    return r.name;
  var e = W2.call(V2.call(r), /^function\s*([\w$]+)/);
  return e ? e[1] : null;
}
function Jm(r, e) {
  if (r.indexOf)
    return r.indexOf(e);
  for (var t = 0, i = r.length; t < i; t++)
    if (r[t] === e)
      return t;
  return -1;
}
function tx(r) {
  if (!Va || !r || typeof r != "object")
    return !1;
  try {
    Va.call(r);
    try {
      Wa.call(r);
    } catch {
      return !0;
    }
    return r instanceof Map;
  } catch {
  }
  return !1;
}
function ix(r) {
  if (!tn || !r || typeof r != "object")
    return !1;
  try {
    tn.call(r, tn);
    try {
      sn.call(r, sn);
    } catch {
      return !0;
    }
    return r instanceof WeakMap;
  } catch {
  }
  return !1;
}
function sx(r) {
  if (!Gh || !r || typeof r != "object")
    return !1;
  try {
    return Gh.call(r), !0;
  } catch {
  }
  return !1;
}
function rx(r) {
  if (!Wa || !r || typeof r != "object")
    return !1;
  try {
    Wa.call(r);
    try {
      Va.call(r);
    } catch {
      return !0;
    }
    return r instanceof Set;
  } catch {
  }
  return !1;
}
function nx(r) {
  if (!sn || !r || typeof r != "object")
    return !1;
  try {
    sn.call(r, sn);
    try {
      tn.call(r, tn);
    } catch {
      return !0;
    }
    return r instanceof WeakSet;
  } catch {
  }
  return !1;
}
function ax(r) {
  return !r || typeof r != "object" ? !1 : typeof HTMLElement < "u" && r instanceof HTMLElement ? !0 : typeof r.nodeName == "string" && typeof r.getAttribute == "function";
}
function qm(r, e) {
  if (r.length > e.maxStringLength) {
    var t = r.length - e.maxStringLength, i = "... " + t + " more character" + (t > 1 ? "s" : "");
    return qm(od.call(r, 0, e.maxStringLength), e) + i;
  }
  var s = $2[e.quoteStyle || "single"];
  s.lastIndex = 0;
  var n = us.call(us.call(r, s, "\\$1"), /[\x00-\x1f]/g, ox);
  return jm(n, "single", e);
}
function ox(r) {
  var e = r.charCodeAt(0), t = {
    8: "b",
    9: "t",
    10: "n",
    12: "f",
    13: "r"
  }[e];
  return t ? "\\" + t : "\\x" + (e < 16 ? "0" : "") + H2.call(e.toString(16));
}
function Vr(r) {
  return "Object(" + r + ")";
}
function hl(r) {
  return r + " { ? }";
}
function Yh(r, e, t, i) {
  var s = i ? j0(t, i) : bi.call(t, ", ");
  return r + " (" + e + ") {" + s + "}";
}
function lx(r) {
  for (var e = 0; e < r.length; e++)
    if (Jm(r[e], `
`) >= 0)
      return !1;
  return !0;
}
function cx(r, e) {
  var t;
  if (r.indent === "	")
    t = "	";
  else if (typeof r.indent == "number" && r.indent > 0)
    t = bi.call(Array(r.indent + 1), " ");
  else
    return null;
  return {
    base: t,
    prev: bi.call(Array(e + 1), t)
  };
}
function j0(r, e) {
  if (r.length === 0)
    return "";
  var t = `
` + e.prev + e.base;
  return t + bi.call(r, "," + t) + `
` + e.prev;
}
function Gn(r, e) {
  var t = z0(r), i = [];
  if (t) {
    i.length = r.length;
    for (var s = 0; s < r.length; s++)
      i[s] = Hi(r, s) ? e(r[s], r) : "";
  }
  var n = typeof dl == "function" ? dl(r) : [], a;
  if (Lr) {
    a = {};
    for (var o = 0; o < n.length; o++)
      a["$" + n[o]] = n[o];
  }
  for (var c in r)
    Hi(r, c) && (t && String(Number(c)) === c && c < r.length || Lr && a["$" + c] instanceof Symbol || (Xm.call(/[^\w$]/, c) ? i.push(e(c, r) + ": " + e(r[c], r)) : i.push(c + ": " + e(r[c], r))));
  if (typeof dl == "function")
    for (var l = 0; l < n.length; l++)
      Ym.call(r, n[l]) && i.push("[" + e(n[l]) + "]: " + e(r[n[l]], r));
  return i;
}
var dx = vo, hx = Or, Eo = function(r, e, t) {
  for (var i = r, s; (s = i.next) != null; i = s)
    if (s.key === e)
      return i.next = s.next, t || (s.next = /** @type {NonNullable<typeof list.next>} */
      r.next, r.next = s), s;
}, ux = function(r, e) {
  if (r) {
    var t = Eo(r, e);
    return t && t.value;
  }
}, fx = function(r, e, t) {
  var i = Eo(r, e);
  i ? i.value = t : r.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
  {
    // eslint-disable-line no-param-reassign, no-extra-parens
    key: e,
    next: r.next,
    value: t
  };
}, px = function(r, e) {
  return r ? !!Eo(r, e) : !1;
}, mx = function(r, e) {
  if (r)
    return Eo(r, e, !0);
}, gx = function() {
  var e, t = {
    assert: function(i) {
      if (!t.has(i))
        throw new hx("Side channel does not contain " + dx(i));
    },
    delete: function(i) {
      var s = e && e.next, n = mx(e, i);
      return n && s && s === n && (e = void 0), !!n;
    },
    get: function(i) {
      return ux(e, i);
    },
    has: function(i) {
      return px(e, i);
    },
    set: function(i, s) {
      e || (e = {
        next: void 0
      }), fx(
        /** @type {NonNullable<typeof $o>} */
        e,
        i,
        s
      );
    }
  };
  return t;
}, e1 = Object, _x = Error, yx = EvalError, xx = RangeError, vx = ReferenceError, Ex = SyntaxError, Sx = URIError, Tx = Math.abs, bx = Math.floor, Ax = Math.max, Cx = Math.min, Rx = Math.pow, Ix = Math.round, Lx = Number.isNaN || function(e) {
  return e !== e;
}, Dx = Lx, Px = function(e) {
  return Dx(e) || e === 0 ? e : e < 0 ? -1 : 1;
}, kx = Object.getOwnPropertyDescriptor, ma = kx;
if (ma)
  try {
    ma([], "length");
  } catch {
    ma = null;
  }
var t1 = ma, ga = Object.defineProperty || !1;
if (ga)
  try {
    ga({}, "a", { value: 1 });
  } catch {
    ga = !1;
  }
var wx = ga, ul, zh;
function Mx() {
  return zh || (zh = 1, ul = function() {
    if (typeof Symbol != "function" || typeof Object.getOwnPropertySymbols != "function")
      return !1;
    if (typeof Symbol.iterator == "symbol")
      return !0;
    var e = {}, t = Symbol("test"), i = Object(t);
    if (typeof t == "string" || Object.prototype.toString.call(t) !== "[object Symbol]" || Object.prototype.toString.call(i) !== "[object Symbol]")
      return !1;
    var s = 42;
    e[t] = s;
    for (var n in e)
      return !1;
    if (typeof Object.keys == "function" && Object.keys(e).length !== 0 || typeof Object.getOwnPropertyNames == "function" && Object.getOwnPropertyNames(e).length !== 0)
      return !1;
    var a = Object.getOwnPropertySymbols(e);
    if (a.length !== 1 || a[0] !== t || !Object.prototype.propertyIsEnumerable.call(e, t))
      return !1;
    if (typeof Object.getOwnPropertyDescriptor == "function") {
      var o = (
        /** @type {PropertyDescriptor} */
        Object.getOwnPropertyDescriptor(e, t)
      );
      if (o.value !== s || o.enumerable !== !0)
        return !1;
    }
    return !0;
  }), ul;
}
var fl, jh;
function Bx() {
  if (jh) return fl;
  jh = 1;
  var r = typeof Symbol < "u" && Symbol, e = Mx();
  return fl = function() {
    return typeof r != "function" || typeof Symbol != "function" || typeof r("foo") != "symbol" || typeof Symbol("bar") != "symbol" ? !1 : e();
  }, fl;
}
var pl, Qh;
function i1() {
  return Qh || (Qh = 1, pl = typeof Reflect < "u" && Reflect.getPrototypeOf || null), pl;
}
var ml, Jh;
function s1() {
  if (Jh) return ml;
  Jh = 1;
  var r = e1;
  return ml = r.getPrototypeOf || null, ml;
}
var Fx = "Function.prototype.bind called on incompatible ", Ox = Object.prototype.toString, Nx = Math.max, Gx = "[object Function]", qh = function(e, t) {
  for (var i = [], s = 0; s < e.length; s += 1)
    i[s] = e[s];
  for (var n = 0; n < t.length; n += 1)
    i[n + e.length] = t[n];
  return i;
}, Ux = function(e, t) {
  for (var i = [], s = t, n = 0; s < e.length; s += 1, n += 1)
    i[n] = e[s];
  return i;
}, Vx = function(r, e) {
  for (var t = "", i = 0; i < r.length; i += 1)
    t += r[i], i + 1 < r.length && (t += e);
  return t;
}, Wx = function(e) {
  var t = this;
  if (typeof t != "function" || Ox.apply(t) !== Gx)
    throw new TypeError(Fx + t);
  for (var i = Ux(arguments, 1), s, n = function() {
    if (this instanceof s) {
      var d = t.apply(
        this,
        qh(i, arguments)
      );
      return Object(d) === d ? d : this;
    }
    return t.apply(
      e,
      qh(i, arguments)
    );
  }, a = Nx(0, t.length - i.length), o = [], c = 0; c < a; c++)
    o[c] = "$" + c;
  if (s = Function("binder", "return function (" + Vx(o, ",") + "){ return binder.apply(this,arguments); }")(n), t.prototype) {
    var l = function() {
    };
    l.prototype = t.prototype, s.prototype = new l(), l.prototype = null;
  }
  return s;
}, Hx = Wx, So = Function.prototype.bind || Hx, ld = Function.prototype.call, gl, eu;
function r1() {
  return eu || (eu = 1, gl = Function.prototype.apply), gl;
}
var Zx = typeof Reflect < "u" && Reflect && Reflect.apply, $x = So, Kx = r1(), Xx = ld, Yx = Zx, zx = Yx || $x.call(Xx, Kx), jx = So, Qx = Or, Jx = ld, qx = zx, n1 = function(e) {
  if (e.length < 1 || typeof e[0] != "function")
    throw new Qx("a function is required");
  return qx(jx, Jx, e);
}, _l, tu;
function ev() {
  if (tu) return _l;
  tu = 1;
  var r = n1, e = t1, t;
  try {
    t = /** @type {{ __proto__?: typeof Array.prototype }} */
    [].__proto__ === Array.prototype;
  } catch (a) {
    if (!a || typeof a != "object" || !("code" in a) || a.code !== "ERR_PROTO_ACCESS")
      throw a;
  }
  var i = !!t && e && e(
    Object.prototype,
    /** @type {keyof typeof Object.prototype} */
    "__proto__"
  ), s = Object, n = s.getPrototypeOf;
  return _l = i && typeof i.get == "function" ? r([i.get]) : typeof n == "function" ? (
    /** @type {import('./get')} */
    function(o) {
      return n(o == null ? o : s(o));
    }
  ) : !1, _l;
}
var yl, iu;
function tv() {
  if (iu) return yl;
  iu = 1;
  var r = i1(), e = s1(), t = ev();
  return yl = r ? function(s) {
    return r(s);
  } : e ? function(s) {
    if (!s || typeof s != "object" && typeof s != "function")
      throw new TypeError("getProto: not an object");
    return e(s);
  } : t ? function(s) {
    return t(s);
  } : null, yl;
}
var xl, su;
function iv() {
  if (su) return xl;
  su = 1;
  var r = Function.prototype.call, e = Object.prototype.hasOwnProperty, t = So;
  return xl = t.call(r, e), xl;
}
var _e, sv = e1, rv = _x, nv = yx, av = xx, ov = vx, Dr = Ex, xr = Or, lv = Sx, cv = Tx, dv = bx, hv = Ax, uv = Cx, fv = Rx, pv = Ix, mv = Px, a1 = Function, vl = function(r) {
  try {
    return a1('"use strict"; return (' + r + ").constructor;")();
  } catch {
  }
}, pn = t1, gv = wx, El = function() {
  throw new xr();
}, _v = pn ? function() {
  try {
    return arguments.callee, El;
  } catch {
    try {
      return pn(arguments, "callee").get;
    } catch {
      return El;
    }
  }
}() : El, Js = Bx()(), dt = tv(), yv = s1(), xv = i1(), o1 = r1(), In = ld, nr = {}, vv = typeof Uint8Array > "u" || !dt ? _e : dt(Uint8Array), ws = {
  __proto__: null,
  "%AggregateError%": typeof AggregateError > "u" ? _e : AggregateError,
  "%Array%": Array,
  "%ArrayBuffer%": typeof ArrayBuffer > "u" ? _e : ArrayBuffer,
  "%ArrayIteratorPrototype%": Js && dt ? dt([][Symbol.iterator]()) : _e,
  "%AsyncFromSyncIteratorPrototype%": _e,
  "%AsyncFunction%": nr,
  "%AsyncGenerator%": nr,
  "%AsyncGeneratorFunction%": nr,
  "%AsyncIteratorPrototype%": nr,
  "%Atomics%": typeof Atomics > "u" ? _e : Atomics,
  "%BigInt%": typeof BigInt > "u" ? _e : BigInt,
  "%BigInt64Array%": typeof BigInt64Array > "u" ? _e : BigInt64Array,
  "%BigUint64Array%": typeof BigUint64Array > "u" ? _e : BigUint64Array,
  "%Boolean%": Boolean,
  "%DataView%": typeof DataView > "u" ? _e : DataView,
  "%Date%": Date,
  "%decodeURI%": decodeURI,
  "%decodeURIComponent%": decodeURIComponent,
  "%encodeURI%": encodeURI,
  "%encodeURIComponent%": encodeURIComponent,
  "%Error%": rv,
  "%eval%": eval,
  // eslint-disable-line no-eval
  "%EvalError%": nv,
  "%Float16Array%": typeof Float16Array > "u" ? _e : Float16Array,
  "%Float32Array%": typeof Float32Array > "u" ? _e : Float32Array,
  "%Float64Array%": typeof Float64Array > "u" ? _e : Float64Array,
  "%FinalizationRegistry%": typeof FinalizationRegistry > "u" ? _e : FinalizationRegistry,
  "%Function%": a1,
  "%GeneratorFunction%": nr,
  "%Int8Array%": typeof Int8Array > "u" ? _e : Int8Array,
  "%Int16Array%": typeof Int16Array > "u" ? _e : Int16Array,
  "%Int32Array%": typeof Int32Array > "u" ? _e : Int32Array,
  "%isFinite%": isFinite,
  "%isNaN%": isNaN,
  "%IteratorPrototype%": Js && dt ? dt(dt([][Symbol.iterator]())) : _e,
  "%JSON%": typeof JSON == "object" ? JSON : _e,
  "%Map%": typeof Map > "u" ? _e : Map,
  "%MapIteratorPrototype%": typeof Map > "u" || !Js || !dt ? _e : dt((/* @__PURE__ */ new Map())[Symbol.iterator]()),
  "%Math%": Math,
  "%Number%": Number,
  "%Object%": sv,
  "%Object.getOwnPropertyDescriptor%": pn,
  "%parseFloat%": parseFloat,
  "%parseInt%": parseInt,
  "%Promise%": typeof Promise > "u" ? _e : Promise,
  "%Proxy%": typeof Proxy > "u" ? _e : Proxy,
  "%RangeError%": av,
  "%ReferenceError%": ov,
  "%Reflect%": typeof Reflect > "u" ? _e : Reflect,
  "%RegExp%": RegExp,
  "%Set%": typeof Set > "u" ? _e : Set,
  "%SetIteratorPrototype%": typeof Set > "u" || !Js || !dt ? _e : dt((/* @__PURE__ */ new Set())[Symbol.iterator]()),
  "%SharedArrayBuffer%": typeof SharedArrayBuffer > "u" ? _e : SharedArrayBuffer,
  "%String%": String,
  "%StringIteratorPrototype%": Js && dt ? dt(""[Symbol.iterator]()) : _e,
  "%Symbol%": Js ? Symbol : _e,
  "%SyntaxError%": Dr,
  "%ThrowTypeError%": _v,
  "%TypedArray%": vv,
  "%TypeError%": xr,
  "%Uint8Array%": typeof Uint8Array > "u" ? _e : Uint8Array,
  "%Uint8ClampedArray%": typeof Uint8ClampedArray > "u" ? _e : Uint8ClampedArray,
  "%Uint16Array%": typeof Uint16Array > "u" ? _e : Uint16Array,
  "%Uint32Array%": typeof Uint32Array > "u" ? _e : Uint32Array,
  "%URIError%": lv,
  "%WeakMap%": typeof WeakMap > "u" ? _e : WeakMap,
  "%WeakRef%": typeof WeakRef > "u" ? _e : WeakRef,
  "%WeakSet%": typeof WeakSet > "u" ? _e : WeakSet,
  "%Function.prototype.call%": In,
  "%Function.prototype.apply%": o1,
  "%Object.defineProperty%": gv,
  "%Object.getPrototypeOf%": yv,
  "%Math.abs%": cv,
  "%Math.floor%": dv,
  "%Math.max%": hv,
  "%Math.min%": uv,
  "%Math.pow%": fv,
  "%Math.round%": pv,
  "%Math.sign%": mv,
  "%Reflect.getPrototypeOf%": xv
};
if (dt)
  try {
    null.error;
  } catch (r) {
    var Ev = dt(dt(r));
    ws["%Error.prototype%"] = Ev;
  }
var Sv = function r(e) {
  var t;
  if (e === "%AsyncFunction%")
    t = vl("async function () {}");
  else if (e === "%GeneratorFunction%")
    t = vl("function* () {}");
  else if (e === "%AsyncGeneratorFunction%")
    t = vl("async function* () {}");
  else if (e === "%AsyncGenerator%") {
    var i = r("%AsyncGeneratorFunction%");
    i && (t = i.prototype);
  } else if (e === "%AsyncIteratorPrototype%") {
    var s = r("%AsyncGenerator%");
    s && dt && (t = dt(s.prototype));
  }
  return ws[e] = t, t;
}, ru = {
  __proto__: null,
  "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
  "%ArrayPrototype%": ["Array", "prototype"],
  "%ArrayProto_entries%": ["Array", "prototype", "entries"],
  "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
  "%ArrayProto_keys%": ["Array", "prototype", "keys"],
  "%ArrayProto_values%": ["Array", "prototype", "values"],
  "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
  "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
  "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
  "%BooleanPrototype%": ["Boolean", "prototype"],
  "%DataViewPrototype%": ["DataView", "prototype"],
  "%DatePrototype%": ["Date", "prototype"],
  "%ErrorPrototype%": ["Error", "prototype"],
  "%EvalErrorPrototype%": ["EvalError", "prototype"],
  "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
  "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
  "%FunctionPrototype%": ["Function", "prototype"],
  "%Generator%": ["GeneratorFunction", "prototype"],
  "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
  "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
  "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
  "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
  "%JSONParse%": ["JSON", "parse"],
  "%JSONStringify%": ["JSON", "stringify"],
  "%MapPrototype%": ["Map", "prototype"],
  "%NumberPrototype%": ["Number", "prototype"],
  "%ObjectPrototype%": ["Object", "prototype"],
  "%ObjProto_toString%": ["Object", "prototype", "toString"],
  "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
  "%PromisePrototype%": ["Promise", "prototype"],
  "%PromiseProto_then%": ["Promise", "prototype", "then"],
  "%Promise_all%": ["Promise", "all"],
  "%Promise_reject%": ["Promise", "reject"],
  "%Promise_resolve%": ["Promise", "resolve"],
  "%RangeErrorPrototype%": ["RangeError", "prototype"],
  "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
  "%RegExpPrototype%": ["RegExp", "prototype"],
  "%SetPrototype%": ["Set", "prototype"],
  "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
  "%StringPrototype%": ["String", "prototype"],
  "%SymbolPrototype%": ["Symbol", "prototype"],
  "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
  "%TypedArrayPrototype%": ["TypedArray", "prototype"],
  "%TypeErrorPrototype%": ["TypeError", "prototype"],
  "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
  "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
  "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
  "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
  "%URIErrorPrototype%": ["URIError", "prototype"],
  "%WeakMapPrototype%": ["WeakMap", "prototype"],
  "%WeakSetPrototype%": ["WeakSet", "prototype"]
}, Ln = So, Ha = iv(), Tv = Ln.call(In, Array.prototype.concat), bv = Ln.call(o1, Array.prototype.splice), nu = Ln.call(In, String.prototype.replace), Za = Ln.call(In, String.prototype.slice), Av = Ln.call(In, RegExp.prototype.exec), Cv = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g, Rv = /\\(\\)?/g, Iv = function(e) {
  var t = Za(e, 0, 1), i = Za(e, -1);
  if (t === "%" && i !== "%")
    throw new Dr("invalid intrinsic syntax, expected closing `%`");
  if (i === "%" && t !== "%")
    throw new Dr("invalid intrinsic syntax, expected opening `%`");
  var s = [];
  return nu(e, Cv, function(n, a, o, c) {
    s[s.length] = o ? nu(c, Rv, "$1") : a || n;
  }), s;
}, Lv = function(e, t) {
  var i = e, s;
  if (Ha(ru, i) && (s = ru[i], i = "%" + s[0] + "%"), Ha(ws, i)) {
    var n = ws[i];
    if (n === nr && (n = Sv(i)), typeof n > "u" && !t)
      throw new xr("intrinsic " + e + " exists, but is not available. Please file an issue!");
    return {
      alias: s,
      name: i,
      value: n
    };
  }
  throw new Dr("intrinsic " + e + " does not exist!");
}, cd = function(e, t) {
  if (typeof e != "string" || e.length === 0)
    throw new xr("intrinsic name must be a non-empty string");
  if (arguments.length > 1 && typeof t != "boolean")
    throw new xr('"allowMissing" argument must be a boolean');
  if (Av(/^%?[^%]*%?$/, e) === null)
    throw new Dr("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
  var i = Iv(e), s = i.length > 0 ? i[0] : "", n = Lv("%" + s + "%", t), a = n.name, o = n.value, c = !1, l = n.alias;
  l && (s = l[0], bv(i, Tv([0, 1], l)));
  for (var d = 1, h = !0; d < i.length; d += 1) {
    var u = i[d], f = Za(u, 0, 1), p = Za(u, -1);
    if ((f === '"' || f === "'" || f === "`" || p === '"' || p === "'" || p === "`") && f !== p)
      throw new Dr("property names with quotes must have matching quotes");
    if ((u === "constructor" || !h) && (c = !0), s += "." + u, a = "%" + s + "%", Ha(ws, a))
      o = ws[a];
    else if (o != null) {
      if (!(u in o)) {
        if (!t)
          throw new xr("base intrinsic for " + e + " exists, but the property is not available.");
        return;
      }
      if (pn && d + 1 >= i.length) {
        var m = pn(o, u);
        h = !!m, h && "get" in m && !("originalValue" in m.get) ? o = m.get : o = o[u];
      } else
        h = Ha(o, u), o = o[u];
      h && !c && (ws[a] = o);
    }
  }
  return o;
}, l1 = cd, c1 = n1, Dv = c1([l1("%String.prototype.indexOf%")]), d1 = function(e, t) {
  var i = (
    /** @type {(this: unknown, ...args: unknown[]) => unknown} */
    l1(e, !!t)
  );
  return typeof i == "function" && Dv(e, ".prototype.") > -1 ? c1(
    /** @type {const} */
    [i]
  ) : i;
}, Pv = cd, Dn = d1, kv = vo, wv = Or, au = Pv("%Map%", !0), Mv = Dn("Map.prototype.get", !0), Bv = Dn("Map.prototype.set", !0), Fv = Dn("Map.prototype.has", !0), Ov = Dn("Map.prototype.delete", !0), Nv = Dn("Map.prototype.size", !0), h1 = !!au && /** @type {Exclude<import('.'), false>} */
function() {
  var e, t = {
    assert: function(i) {
      if (!t.has(i))
        throw new wv("Side channel does not contain " + kv(i));
    },
    delete: function(i) {
      if (e) {
        var s = Ov(e, i);
        return Nv(e) === 0 && (e = void 0), s;
      }
      return !1;
    },
    get: function(i) {
      if (e)
        return Mv(e, i);
    },
    has: function(i) {
      return e ? Fv(e, i) : !1;
    },
    set: function(i, s) {
      e || (e = new au()), Bv(e, i, s);
    }
  };
  return t;
}, Gv = cd, To = d1, Uv = vo, Un = h1, Vv = Or, qs = Gv("%WeakMap%", !0), Wv = To("WeakMap.prototype.get", !0), Hv = To("WeakMap.prototype.set", !0), Zv = To("WeakMap.prototype.has", !0), $v = To("WeakMap.prototype.delete", !0), Kv = qs ? (
  /** @type {Exclude<import('.'), false>} */
  function() {
    var e, t, i = {
      assert: function(s) {
        if (!i.has(s))
          throw new Vv("Side channel does not contain " + Uv(s));
      },
      delete: function(s) {
        if (qs && s && (typeof s == "object" || typeof s == "function")) {
          if (e)
            return $v(e, s);
        } else if (Un && t)
          return t.delete(s);
        return !1;
      },
      get: function(s) {
        return qs && s && (typeof s == "object" || typeof s == "function") && e ? Wv(e, s) : t && t.get(s);
      },
      has: function(s) {
        return qs && s && (typeof s == "object" || typeof s == "function") && e ? Zv(e, s) : !!t && t.has(s);
      },
      set: function(s, n) {
        qs && s && (typeof s == "object" || typeof s == "function") ? (e || (e = new qs()), Hv(e, s, n)) : Un && (t || (t = Un()), t.set(s, n));
      }
    };
    return i;
  }
) : Un, Xv = Or, Yv = vo, zv = gx, jv = h1, Qv = Kv, Jv = Qv || jv || zv, qv = function() {
  var e, t = {
    assert: function(i) {
      if (!t.has(i))
        throw new Xv("Side channel does not contain " + Yv(i));
    },
    delete: function(i) {
      return !!e && e.delete(i);
    },
    get: function(i) {
      return e && e.get(i);
    },
    has: function(i) {
      return !!e && e.has(i);
    },
    set: function(i, s) {
      e || (e = Jv()), e.set(i, s);
    }
  };
  return t;
}, eE = String.prototype.replace, tE = /%20/g, Sl = {
  RFC1738: "RFC1738",
  RFC3986: "RFC3986"
}, dd = {
  default: Sl.RFC3986,
  formatters: {
    RFC1738: function(r) {
      return eE.call(r, tE, "+");
    },
    RFC3986: function(r) {
      return String(r);
    }
  },
  RFC1738: Sl.RFC1738,
  RFC3986: Sl.RFC3986
}, iE = dd, Tl = Object.prototype.hasOwnProperty, Ps = Array.isArray, mi = function() {
  for (var r = [], e = 0; e < 256; ++e)
    r.push("%" + ((e < 16 ? "0" : "") + e.toString(16)).toUpperCase());
  return r;
}(), sE = function(e) {
  for (; e.length > 1; ) {
    var t = e.pop(), i = t.obj[t.prop];
    if (Ps(i)) {
      for (var s = [], n = 0; n < i.length; ++n)
        typeof i[n] < "u" && s.push(i[n]);
      t.obj[t.prop] = s;
    }
  }
}, u1 = function(e, t) {
  for (var i = t && t.plainObjects ? { __proto__: null } : {}, s = 0; s < e.length; ++s)
    typeof e[s] < "u" && (i[s] = e[s]);
  return i;
}, rE = function r(e, t, i) {
  if (!t)
    return e;
  if (typeof t != "object" && typeof t != "function") {
    if (Ps(e))
      e.push(t);
    else if (e && typeof e == "object")
      (i && (i.plainObjects || i.allowPrototypes) || !Tl.call(Object.prototype, t)) && (e[t] = !0);
    else
      return [e, t];
    return e;
  }
  if (!e || typeof e != "object")
    return [e].concat(t);
  var s = e;
  return Ps(e) && !Ps(t) && (s = u1(e, i)), Ps(e) && Ps(t) ? (t.forEach(function(n, a) {
    if (Tl.call(e, a)) {
      var o = e[a];
      o && typeof o == "object" && n && typeof n == "object" ? e[a] = r(o, n, i) : e.push(n);
    } else
      e[a] = n;
  }), e) : Object.keys(t).reduce(function(n, a) {
    var o = t[a];
    return Tl.call(n, a) ? n[a] = r(n[a], o, i) : n[a] = o, n;
  }, s);
}, nE = function(e, t) {
  return Object.keys(t).reduce(function(i, s) {
    return i[s] = t[s], i;
  }, e);
}, aE = function(r, e, t) {
  var i = r.replace(/\+/g, " ");
  if (t === "iso-8859-1")
    return i.replace(/%[0-9a-f]{2}/gi, unescape);
  try {
    return decodeURIComponent(i);
  } catch {
    return i;
  }
}, bl = 1024, oE = function(e, t, i, s, n) {
  if (e.length === 0)
    return e;
  var a = e;
  if (typeof e == "symbol" ? a = Symbol.prototype.toString.call(e) : typeof e != "string" && (a = String(e)), i === "iso-8859-1")
    return escape(a).replace(/%u[0-9a-f]{4}/gi, function(f) {
      return "%26%23" + parseInt(f.slice(2), 16) + "%3B";
    });
  for (var o = "", c = 0; c < a.length; c += bl) {
    for (var l = a.length >= bl ? a.slice(c, c + bl) : a, d = [], h = 0; h < l.length; ++h) {
      var u = l.charCodeAt(h);
      if (u === 45 || u === 46 || u === 95 || u === 126 || u >= 48 && u <= 57 || u >= 65 && u <= 90 || u >= 97 && u <= 122 || n === iE.RFC1738 && (u === 40 || u === 41)) {
        d[d.length] = l.charAt(h);
        continue;
      }
      if (u < 128) {
        d[d.length] = mi[u];
        continue;
      }
      if (u < 2048) {
        d[d.length] = mi[192 | u >> 6] + mi[128 | u & 63];
        continue;
      }
      if (u < 55296 || u >= 57344) {
        d[d.length] = mi[224 | u >> 12] + mi[128 | u >> 6 & 63] + mi[128 | u & 63];
        continue;
      }
      h += 1, u = 65536 + ((u & 1023) << 10 | l.charCodeAt(h) & 1023), d[d.length] = mi[240 | u >> 18] + mi[128 | u >> 12 & 63] + mi[128 | u >> 6 & 63] + mi[128 | u & 63];
    }
    o += d.join("");
  }
  return o;
}, lE = function(e) {
  for (var t = [{ obj: { o: e }, prop: "o" }], i = [], s = 0; s < t.length; ++s)
    for (var n = t[s], a = n.obj[n.prop], o = Object.keys(a), c = 0; c < o.length; ++c) {
      var l = o[c], d = a[l];
      typeof d == "object" && d !== null && i.indexOf(d) === -1 && (t.push({ obj: a, prop: l }), i.push(d));
    }
  return sE(t), e;
}, cE = function(e) {
  return Object.prototype.toString.call(e) === "[object RegExp]";
}, dE = function(e) {
  return !e || typeof e != "object" ? !1 : !!(e.constructor && e.constructor.isBuffer && e.constructor.isBuffer(e));
}, hE = function(e, t) {
  return [].concat(e, t);
}, uE = function(e, t) {
  if (Ps(e)) {
    for (var i = [], s = 0; s < e.length; s += 1)
      i.push(t(e[s]));
    return i;
  }
  return t(e);
}, f1 = {
  arrayToObject: u1,
  assign: nE,
  combine: hE,
  compact: lE,
  decode: aE,
  encode: oE,
  isBuffer: dE,
  isRegExp: cE,
  maybeMap: uE,
  merge: rE
}, p1 = qv, _a = f1, nn = dd, fE = Object.prototype.hasOwnProperty, m1 = {
  brackets: function(e) {
    return e + "[]";
  },
  comma: "comma",
  indices: function(e, t) {
    return e + "[" + t + "]";
  },
  repeat: function(e) {
    return e;
  }
}, Ti = Array.isArray, pE = Array.prototype.push, g1 = function(r, e) {
  pE.apply(r, Ti(e) ? e : [e]);
}, mE = Date.prototype.toISOString, ou = nn.default, it = {
  addQueryPrefix: !1,
  allowDots: !1,
  allowEmptyArrays: !1,
  arrayFormat: "indices",
  charset: "utf-8",
  charsetSentinel: !1,
  commaRoundTrip: !1,
  delimiter: "&",
  encode: !0,
  encodeDotInKeys: !1,
  encoder: _a.encode,
  encodeValuesOnly: !1,
  filter: void 0,
  format: ou,
  formatter: nn.formatters[ou],
  // deprecated
  indices: !1,
  serializeDate: function(e) {
    return mE.call(e);
  },
  skipNulls: !1,
  strictNullHandling: !1
}, gE = function(e) {
  return typeof e == "string" || typeof e == "number" || typeof e == "boolean" || typeof e == "symbol" || typeof e == "bigint";
}, Al = {}, _E = function r(e, t, i, s, n, a, o, c, l, d, h, u, f, p, m, g, x, _) {
  for (var v = e, E = _, b = 0, A = !1; (E = E.get(Al)) !== void 0 && !A; ) {
    var C = E.get(e);
    if (b += 1, typeof C < "u") {
      if (C === b)
        throw new RangeError("Cyclic object value");
      A = !0;
    }
    typeof E.get(Al) > "u" && (b = 0);
  }
  if (typeof d == "function" ? v = d(t, v) : v instanceof Date ? v = f(v) : i === "comma" && Ti(v) && (v = _a.maybeMap(v, function(W) {
    return W instanceof Date ? f(W) : W;
  })), v === null) {
    if (a)
      return l && !g ? l(t, it.encoder, x, "key", p) : t;
    v = "";
  }
  if (gE(v) || _a.isBuffer(v)) {
    if (l) {
      var I = g ? t : l(t, it.encoder, x, "key", p);
      return [m(I) + "=" + m(l(v, it.encoder, x, "value", p))];
    }
    return [m(t) + "=" + m(String(v))];
  }
  var L = [];
  if (typeof v > "u")
    return L;
  var R;
  if (i === "comma" && Ti(v))
    g && l && (v = _a.maybeMap(v, l)), R = [{ value: v.length > 0 ? v.join(",") || null : void 0 }];
  else if (Ti(d))
    R = d;
  else {
    var D = Object.keys(v);
    R = h ? D.sort(h) : D;
  }
  var M = c ? String(t).replace(/\./g, "%2E") : String(t), w = s && Ti(v) && v.length === 1 ? M + "[]" : M;
  if (n && Ti(v) && v.length === 0)
    return w + "[]";
  for (var N = 0; N < R.length; ++N) {
    var H = R[N], G = typeof H == "object" && H && typeof H.value < "u" ? H.value : v[H];
    if (!(o && G === null)) {
      var Z = u && c ? String(H).replace(/\./g, "%2E") : String(H), $ = Ti(v) ? typeof i == "function" ? i(w, Z) : w : w + (u ? "." + Z : "[" + Z + "]");
      _.set(e, b);
      var Y = p1();
      Y.set(Al, _), g1(L, r(
        G,
        $,
        i,
        s,
        n,
        a,
        o,
        c,
        i === "comma" && g && Ti(v) ? null : l,
        d,
        h,
        u,
        f,
        p,
        m,
        g,
        x,
        Y
      ));
    }
  }
  return L;
}, yE = function(e) {
  if (!e)
    return it;
  if (typeof e.allowEmptyArrays < "u" && typeof e.allowEmptyArrays != "boolean")
    throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
  if (typeof e.encodeDotInKeys < "u" && typeof e.encodeDotInKeys != "boolean")
    throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
  if (e.encoder !== null && typeof e.encoder < "u" && typeof e.encoder != "function")
    throw new TypeError("Encoder has to be a function.");
  var t = e.charset || it.charset;
  if (typeof e.charset < "u" && e.charset !== "utf-8" && e.charset !== "iso-8859-1")
    throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
  var i = nn.default;
  if (typeof e.format < "u") {
    if (!fE.call(nn.formatters, e.format))
      throw new TypeError("Unknown format option provided.");
    i = e.format;
  }
  var s = nn.formatters[i], n = it.filter;
  (typeof e.filter == "function" || Ti(e.filter)) && (n = e.filter);
  var a;
  if (e.arrayFormat in m1 ? a = e.arrayFormat : "indices" in e ? a = e.indices ? "indices" : "repeat" : a = it.arrayFormat, "commaRoundTrip" in e && typeof e.commaRoundTrip != "boolean")
    throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
  var o = typeof e.allowDots > "u" ? e.encodeDotInKeys === !0 ? !0 : it.allowDots : !!e.allowDots;
  return {
    addQueryPrefix: typeof e.addQueryPrefix == "boolean" ? e.addQueryPrefix : it.addQueryPrefix,
    allowDots: o,
    allowEmptyArrays: typeof e.allowEmptyArrays == "boolean" ? !!e.allowEmptyArrays : it.allowEmptyArrays,
    arrayFormat: a,
    charset: t,
    charsetSentinel: typeof e.charsetSentinel == "boolean" ? e.charsetSentinel : it.charsetSentinel,
    commaRoundTrip: !!e.commaRoundTrip,
    delimiter: typeof e.delimiter > "u" ? it.delimiter : e.delimiter,
    encode: typeof e.encode == "boolean" ? e.encode : it.encode,
    encodeDotInKeys: typeof e.encodeDotInKeys == "boolean" ? e.encodeDotInKeys : it.encodeDotInKeys,
    encoder: typeof e.encoder == "function" ? e.encoder : it.encoder,
    encodeValuesOnly: typeof e.encodeValuesOnly == "boolean" ? e.encodeValuesOnly : it.encodeValuesOnly,
    filter: n,
    format: i,
    formatter: s,
    serializeDate: typeof e.serializeDate == "function" ? e.serializeDate : it.serializeDate,
    skipNulls: typeof e.skipNulls == "boolean" ? e.skipNulls : it.skipNulls,
    sort: typeof e.sort == "function" ? e.sort : null,
    strictNullHandling: typeof e.strictNullHandling == "boolean" ? e.strictNullHandling : it.strictNullHandling
  };
}, xE = function(r, e) {
  var t = r, i = yE(e), s, n;
  typeof i.filter == "function" ? (n = i.filter, t = n("", t)) : Ti(i.filter) && (n = i.filter, s = n);
  var a = [];
  if (typeof t != "object" || t === null)
    return "";
  var o = m1[i.arrayFormat], c = o === "comma" && i.commaRoundTrip;
  s || (s = Object.keys(t)), i.sort && s.sort(i.sort);
  for (var l = p1(), d = 0; d < s.length; ++d) {
    var h = s[d], u = t[h];
    i.skipNulls && u === null || g1(a, _E(
      u,
      h,
      o,
      c,
      i.allowEmptyArrays,
      i.strictNullHandling,
      i.skipNulls,
      i.encodeDotInKeys,
      i.encode ? i.encoder : null,
      i.filter,
      i.sort,
      i.allowDots,
      i.serializeDate,
      i.format,
      i.formatter,
      i.encodeValuesOnly,
      i.charset,
      l
    ));
  }
  var f = a.join(i.delimiter), p = i.addQueryPrefix === !0 ? "?" : "";
  return i.charsetSentinel && (i.charset === "iso-8859-1" ? p += "utf8=%26%2310003%3B&" : p += "utf8=%E2%9C%93&"), f.length > 0 ? p + f : "";
}, Fs = f1, Q0 = Object.prototype.hasOwnProperty, lu = Array.isArray, ze = {
  allowDots: !1,
  allowEmptyArrays: !1,
  allowPrototypes: !1,
  allowSparse: !1,
  arrayLimit: 20,
  charset: "utf-8",
  charsetSentinel: !1,
  comma: !1,
  decodeDotInKeys: !1,
  decoder: Fs.decode,
  delimiter: "&",
  depth: 5,
  duplicates: "combine",
  ignoreQueryPrefix: !1,
  interpretNumericEntities: !1,
  parameterLimit: 1e3,
  parseArrays: !0,
  plainObjects: !1,
  strictDepth: !1,
  strictNullHandling: !1,
  throwOnLimitExceeded: !1
}, vE = function(r) {
  return r.replace(/&#(\d+);/g, function(e, t) {
    return String.fromCharCode(parseInt(t, 10));
  });
}, _1 = function(r, e, t) {
  if (r && typeof r == "string" && e.comma && r.indexOf(",") > -1)
    return r.split(",");
  if (e.throwOnLimitExceeded && t >= e.arrayLimit)
    throw new RangeError("Array limit exceeded. Only " + e.arrayLimit + " element" + (e.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
  return r;
}, EE = "utf8=%26%2310003%3B", SE = "utf8=%E2%9C%93", TE = function(e, t) {
  var i = { __proto__: null }, s = t.ignoreQueryPrefix ? e.replace(/^\?/, "") : e;
  s = s.replace(/%5B/gi, "[").replace(/%5D/gi, "]");
  var n = t.parameterLimit === 1 / 0 ? void 0 : t.parameterLimit, a = s.split(
    t.delimiter,
    t.throwOnLimitExceeded ? n + 1 : n
  );
  if (t.throwOnLimitExceeded && a.length > n)
    throw new RangeError("Parameter limit exceeded. Only " + n + " parameter" + (n === 1 ? "" : "s") + " allowed.");
  var o = -1, c, l = t.charset;
  if (t.charsetSentinel)
    for (c = 0; c < a.length; ++c)
      a[c].indexOf("utf8=") === 0 && (a[c] === SE ? l = "utf-8" : a[c] === EE && (l = "iso-8859-1"), o = c, c = a.length);
  for (c = 0; c < a.length; ++c)
    if (c !== o) {
      var d = a[c], h = d.indexOf("]="), u = h === -1 ? d.indexOf("=") : h + 1, f, p;
      u === -1 ? (f = t.decoder(d, ze.decoder, l, "key"), p = t.strictNullHandling ? null : "") : (f = t.decoder(d.slice(0, u), ze.decoder, l, "key"), p = Fs.maybeMap(
        _1(
          d.slice(u + 1),
          t,
          lu(i[f]) ? i[f].length : 0
        ),
        function(g) {
          return t.decoder(g, ze.decoder, l, "value");
        }
      )), p && t.interpretNumericEntities && l === "iso-8859-1" && (p = vE(String(p))), d.indexOf("[]=") > -1 && (p = lu(p) ? [p] : p);
      var m = Q0.call(i, f);
      m && t.duplicates === "combine" ? i[f] = Fs.combine(i[f], p) : (!m || t.duplicates === "last") && (i[f] = p);
    }
  return i;
}, bE = function(r, e, t, i) {
  var s = 0;
  if (r.length > 0 && r[r.length - 1] === "[]") {
    var n = r.slice(0, -1).join("");
    s = Array.isArray(e) && e[n] ? e[n].length : 0;
  }
  for (var a = i ? e : _1(e, t, s), o = r.length - 1; o >= 0; --o) {
    var c, l = r[o];
    if (l === "[]" && t.parseArrays)
      c = t.allowEmptyArrays && (a === "" || t.strictNullHandling && a === null) ? [] : Fs.combine([], a);
    else {
      c = t.plainObjects ? { __proto__: null } : {};
      var d = l.charAt(0) === "[" && l.charAt(l.length - 1) === "]" ? l.slice(1, -1) : l, h = t.decodeDotInKeys ? d.replace(/%2E/g, ".") : d, u = parseInt(h, 10);
      !t.parseArrays && h === "" ? c = { 0: a } : !isNaN(u) && l !== h && String(u) === h && u >= 0 && t.parseArrays && u <= t.arrayLimit ? (c = [], c[u] = a) : h !== "__proto__" && (c[h] = a);
    }
    a = c;
  }
  return a;
}, AE = function(e, t, i, s) {
  if (e) {
    var n = i.allowDots ? e.replace(/\.([^.[]+)/g, "[$1]") : e, a = /(\[[^[\]]*])/, o = /(\[[^[\]]*])/g, c = i.depth > 0 && a.exec(n), l = c ? n.slice(0, c.index) : n, d = [];
    if (l) {
      if (!i.plainObjects && Q0.call(Object.prototype, l) && !i.allowPrototypes)
        return;
      d.push(l);
    }
    for (var h = 0; i.depth > 0 && (c = o.exec(n)) !== null && h < i.depth; ) {
      if (h += 1, !i.plainObjects && Q0.call(Object.prototype, c[1].slice(1, -1)) && !i.allowPrototypes)
        return;
      d.push(c[1]);
    }
    if (c) {
      if (i.strictDepth === !0)
        throw new RangeError("Input depth exceeded depth option of " + i.depth + " and strictDepth is true");
      d.push("[" + n.slice(c.index) + "]");
    }
    return bE(d, t, i, s);
  }
}, CE = function(e) {
  if (!e)
    return ze;
  if (typeof e.allowEmptyArrays < "u" && typeof e.allowEmptyArrays != "boolean")
    throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
  if (typeof e.decodeDotInKeys < "u" && typeof e.decodeDotInKeys != "boolean")
    throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");
  if (e.decoder !== null && typeof e.decoder < "u" && typeof e.decoder != "function")
    throw new TypeError("Decoder has to be a function.");
  if (typeof e.charset < "u" && e.charset !== "utf-8" && e.charset !== "iso-8859-1")
    throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
  if (typeof e.throwOnLimitExceeded < "u" && typeof e.throwOnLimitExceeded != "boolean")
    throw new TypeError("`throwOnLimitExceeded` option must be a boolean");
  var t = typeof e.charset > "u" ? ze.charset : e.charset, i = typeof e.duplicates > "u" ? ze.duplicates : e.duplicates;
  if (i !== "combine" && i !== "first" && i !== "last")
    throw new TypeError("The duplicates option must be either combine, first, or last");
  var s = typeof e.allowDots > "u" ? e.decodeDotInKeys === !0 ? !0 : ze.allowDots : !!e.allowDots;
  return {
    allowDots: s,
    allowEmptyArrays: typeof e.allowEmptyArrays == "boolean" ? !!e.allowEmptyArrays : ze.allowEmptyArrays,
    allowPrototypes: typeof e.allowPrototypes == "boolean" ? e.allowPrototypes : ze.allowPrototypes,
    allowSparse: typeof e.allowSparse == "boolean" ? e.allowSparse : ze.allowSparse,
    arrayLimit: typeof e.arrayLimit == "number" ? e.arrayLimit : ze.arrayLimit,
    charset: t,
    charsetSentinel: typeof e.charsetSentinel == "boolean" ? e.charsetSentinel : ze.charsetSentinel,
    comma: typeof e.comma == "boolean" ? e.comma : ze.comma,
    decodeDotInKeys: typeof e.decodeDotInKeys == "boolean" ? e.decodeDotInKeys : ze.decodeDotInKeys,
    decoder: typeof e.decoder == "function" ? e.decoder : ze.decoder,
    delimiter: typeof e.delimiter == "string" || Fs.isRegExp(e.delimiter) ? e.delimiter : ze.delimiter,
    // eslint-disable-next-line no-implicit-coercion, no-extra-parens
    depth: typeof e.depth == "number" || e.depth === !1 ? +e.depth : ze.depth,
    duplicates: i,
    ignoreQueryPrefix: e.ignoreQueryPrefix === !0,
    interpretNumericEntities: typeof e.interpretNumericEntities == "boolean" ? e.interpretNumericEntities : ze.interpretNumericEntities,
    parameterLimit: typeof e.parameterLimit == "number" ? e.parameterLimit : ze.parameterLimit,
    parseArrays: e.parseArrays !== !1,
    plainObjects: typeof e.plainObjects == "boolean" ? e.plainObjects : ze.plainObjects,
    strictDepth: typeof e.strictDepth == "boolean" ? !!e.strictDepth : ze.strictDepth,
    strictNullHandling: typeof e.strictNullHandling == "boolean" ? e.strictNullHandling : ze.strictNullHandling,
    throwOnLimitExceeded: typeof e.throwOnLimitExceeded == "boolean" ? e.throwOnLimitExceeded : !1
  };
}, RE = function(r, e) {
  var t = CE(e);
  if (r === "" || r === null || typeof r > "u")
    return t.plainObjects ? { __proto__: null } : {};
  for (var i = typeof r == "string" ? TE(r, t) : r, s = t.plainObjects ? { __proto__: null } : {}, n = Object.keys(i), a = 0; a < n.length; ++a) {
    var o = n[a], c = AE(o, i[o], t, typeof r == "string");
    s = Fs.merge(s, c, t);
  }
  return t.allowSparse === !0 ? s : Fs.compact(s);
}, IE = xE, LE = RE, DE = dd, y1 = {
  formats: DE,
  parse: LE,
  stringify: IE
};
const er = /* @__PURE__ */ Fr(y1);
var PE = B2;
function fi() {
  this.protocol = null, this.slashes = null, this.auth = null, this.host = null, this.port = null, this.hostname = null, this.hash = null, this.search = null, this.query = null, this.pathname = null, this.path = null, this.href = null;
}
var kE = /^([a-z0-9.+-]+:)/i, wE = /:[0-9]*$/, ME = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, BE = [
  "<",
  ">",
  '"',
  "`",
  " ",
  "\r",
  `
`,
  "	"
], FE = [
  "{",
  "}",
  "|",
  "\\",
  "^",
  "`"
].concat(BE), J0 = ["'"].concat(FE), cu = [
  "%",
  "/",
  "?",
  ";",
  "#"
].concat(J0), du = [
  "/",
  "?",
  "#"
], OE = 255, hu = /^[+a-z0-9A-Z_-]{0,63}$/, NE = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, GE = {
  javascript: !0,
  "javascript:": !0
}, q0 = {
  javascript: !0,
  "javascript:": !0
}, vr = {
  http: !0,
  https: !0,
  ftp: !0,
  gopher: !0,
  file: !0,
  "http:": !0,
  "https:": !0,
  "ftp:": !0,
  "gopher:": !0,
  "file:": !0
}, ec = y1;
function hd(r, e, t) {
  if (r && typeof r == "object" && r instanceof fi)
    return r;
  var i = new fi();
  return i.parse(r, e, t), i;
}
fi.prototype.parse = function(r, e, t) {
  if (typeof r != "string")
    throw new TypeError("Parameter 'url' must be a string, not " + typeof r);
  var i = r.indexOf("?"), s = i !== -1 && i < r.indexOf("#") ? "?" : "#", n = r.split(s), a = /\\/g;
  n[0] = n[0].replace(a, "/"), r = n.join(s);
  var o = r;
  if (o = o.trim(), !t && r.split("#").length === 1) {
    var c = ME.exec(o);
    if (c)
      return this.path = o, this.href = o, this.pathname = c[1], c[2] ? (this.search = c[2], e ? this.query = ec.parse(this.search.substr(1)) : this.query = this.search.substr(1)) : e && (this.search = "", this.query = {}), this;
  }
  var l = kE.exec(o);
  if (l) {
    l = l[0];
    var d = l.toLowerCase();
    this.protocol = d, o = o.substr(l.length);
  }
  if (t || l || o.match(/^\/\/[^@/]+@[^@/]+/)) {
    var h = o.substr(0, 2) === "//";
    h && !(l && q0[l]) && (o = o.substr(2), this.slashes = !0);
  }
  if (!q0[l] && (h || l && !vr[l])) {
    for (var u = -1, f = 0; f < du.length; f++) {
      var p = o.indexOf(du[f]);
      p !== -1 && (u === -1 || p < u) && (u = p);
    }
    var m, g;
    u === -1 ? g = o.lastIndexOf("@") : g = o.lastIndexOf("@", u), g !== -1 && (m = o.slice(0, g), o = o.slice(g + 1), this.auth = decodeURIComponent(m)), u = -1;
    for (var f = 0; f < cu.length; f++) {
      var p = o.indexOf(cu[f]);
      p !== -1 && (u === -1 || p < u) && (u = p);
    }
    u === -1 && (u = o.length), this.host = o.slice(0, u), o = o.slice(u), this.parseHost(), this.hostname = this.hostname || "";
    var x = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
    if (!x)
      for (var _ = this.hostname.split(/\./), f = 0, v = _.length; f < v; f++) {
        var E = _[f];
        if (E && !E.match(hu)) {
          for (var b = "", A = 0, C = E.length; A < C; A++)
            E.charCodeAt(A) > 127 ? b += "x" : b += E[A];
          if (!b.match(hu)) {
            var I = _.slice(0, f), L = _.slice(f + 1), R = E.match(NE);
            R && (I.push(R[1]), L.unshift(R[2])), L.length && (o = "/" + L.join(".") + o), this.hostname = I.join(".");
            break;
          }
        }
      }
    this.hostname.length > OE ? this.hostname = "" : this.hostname = this.hostname.toLowerCase(), x || (this.hostname = PE.toASCII(this.hostname));
    var D = this.port ? ":" + this.port : "", M = this.hostname || "";
    this.host = M + D, this.href += this.host, x && (this.hostname = this.hostname.substr(1, this.hostname.length - 2), o[0] !== "/" && (o = "/" + o));
  }
  if (!GE[d])
    for (var f = 0, v = J0.length; f < v; f++) {
      var w = J0[f];
      if (o.indexOf(w) !== -1) {
        var N = encodeURIComponent(w);
        N === w && (N = escape(w)), o = o.split(w).join(N);
      }
    }
  var H = o.indexOf("#");
  H !== -1 && (this.hash = o.substr(H), o = o.slice(0, H));
  var G = o.indexOf("?");
  if (G !== -1 ? (this.search = o.substr(G), this.query = o.substr(G + 1), e && (this.query = ec.parse(this.query)), o = o.slice(0, G)) : e && (this.search = "", this.query = {}), o && (this.pathname = o), vr[d] && this.hostname && !this.pathname && (this.pathname = "/"), this.pathname || this.search) {
    var D = this.pathname || "", Z = this.search || "";
    this.path = D + Z;
  }
  return this.href = this.format(), this;
};
function UE(r) {
  return typeof r == "string" && (r = hd(r)), r instanceof fi ? r.format() : fi.prototype.format.call(r);
}
fi.prototype.format = function() {
  var r = this.auth || "";
  r && (r = encodeURIComponent(r), r = r.replace(/%3A/i, ":"), r += "@");
  var e = this.protocol || "", t = this.pathname || "", i = this.hash || "", s = !1, n = "";
  this.host ? s = r + this.host : this.hostname && (s = r + (this.hostname.indexOf(":") === -1 ? this.hostname : "[" + this.hostname + "]"), this.port && (s += ":" + this.port)), this.query && typeof this.query == "object" && Object.keys(this.query).length && (n = ec.stringify(this.query, {
    arrayFormat: "repeat",
    addQueryPrefix: !1
  }));
  var a = this.search || n && "?" + n || "";
  return e && e.substr(-1) !== ":" && (e += ":"), this.slashes || (!e || vr[e]) && s !== !1 ? (s = "//" + (s || ""), t && t.charAt(0) !== "/" && (t = "/" + t)) : s || (s = ""), i && i.charAt(0) !== "#" && (i = "#" + i), a && a.charAt(0) !== "?" && (a = "?" + a), t = t.replace(/[?#]/g, function(o) {
    return encodeURIComponent(o);
  }), a = a.replace("#", "%23"), e + s + t + a + i;
};
fi.prototype.resolve = function(r) {
  return this.resolveObject(hd(r, !1, !0)).format();
};
fi.prototype.resolveObject = function(r) {
  if (typeof r == "string") {
    var e = new fi();
    e.parse(r, !1, !0), r = e;
  }
  for (var t = new fi(), i = Object.keys(this), s = 0; s < i.length; s++) {
    var n = i[s];
    t[n] = this[n];
  }
  if (t.hash = r.hash, r.href === "")
    return t.href = t.format(), t;
  if (r.slashes && !r.protocol) {
    for (var a = Object.keys(r), o = 0; o < a.length; o++) {
      var c = a[o];
      c !== "protocol" && (t[c] = r[c]);
    }
    return vr[t.protocol] && t.hostname && !t.pathname && (t.pathname = "/", t.path = t.pathname), t.href = t.format(), t;
  }
  if (r.protocol && r.protocol !== t.protocol) {
    if (!vr[r.protocol]) {
      for (var l = Object.keys(r), d = 0; d < l.length; d++) {
        var h = l[d];
        t[h] = r[h];
      }
      return t.href = t.format(), t;
    }
    if (t.protocol = r.protocol, !r.host && !q0[r.protocol]) {
      for (var v = (r.pathname || "").split("/"); v.length && !(r.host = v.shift()); )
        ;
      r.host || (r.host = ""), r.hostname || (r.hostname = ""), v[0] !== "" && v.unshift(""), v.length < 2 && v.unshift(""), t.pathname = v.join("/");
    } else
      t.pathname = r.pathname;
    if (t.search = r.search, t.query = r.query, t.host = r.host || "", t.auth = r.auth, t.hostname = r.hostname || r.host, t.port = r.port, t.pathname || t.search) {
      var u = t.pathname || "", f = t.search || "";
      t.path = u + f;
    }
    return t.slashes = t.slashes || r.slashes, t.href = t.format(), t;
  }
  var p = t.pathname && t.pathname.charAt(0) === "/", m = r.host || r.pathname && r.pathname.charAt(0) === "/", g = m || p || t.host && r.pathname, x = g, _ = t.pathname && t.pathname.split("/") || [], v = r.pathname && r.pathname.split("/") || [], E = t.protocol && !vr[t.protocol];
  if (E && (t.hostname = "", t.port = null, t.host && (_[0] === "" ? _[0] = t.host : _.unshift(t.host)), t.host = "", r.protocol && (r.hostname = null, r.port = null, r.host && (v[0] === "" ? v[0] = r.host : v.unshift(r.host)), r.host = null), g = g && (v[0] === "" || _[0] === "")), m)
    t.host = r.host || r.host === "" ? r.host : t.host, t.hostname = r.hostname || r.hostname === "" ? r.hostname : t.hostname, t.search = r.search, t.query = r.query, _ = v;
  else if (v.length)
    _ || (_ = []), _.pop(), _ = _.concat(v), t.search = r.search, t.query = r.query;
  else if (r.search != null) {
    if (E) {
      t.host = _.shift(), t.hostname = t.host;
      var b = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : !1;
      b && (t.auth = b.shift(), t.hostname = b.shift(), t.host = t.hostname);
    }
    return t.search = r.search, t.query = r.query, (t.pathname !== null || t.search !== null) && (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), t.href = t.format(), t;
  }
  if (!_.length)
    return t.pathname = null, t.search ? t.path = "/" + t.search : t.path = null, t.href = t.format(), t;
  for (var A = _.slice(-1)[0], C = (t.host || r.host || _.length > 1) && (A === "." || A === "..") || A === "", I = 0, L = _.length; L >= 0; L--)
    A = _[L], A === "." ? _.splice(L, 1) : A === ".." ? (_.splice(L, 1), I++) : I && (_.splice(L, 1), I--);
  if (!g && !x)
    for (; I--; I)
      _.unshift("..");
  g && _[0] !== "" && (!_[0] || _[0].charAt(0) !== "/") && _.unshift(""), C && _.join("/").substr(-1) !== "/" && _.push("");
  var R = _[0] === "" || _[0] && _[0].charAt(0) === "/";
  if (E) {
    t.hostname = R ? "" : _.length ? _.shift() : "", t.host = t.hostname;
    var b = t.host && t.host.indexOf("@") > 0 ? t.host.split("@") : !1;
    b && (t.auth = b.shift(), t.hostname = b.shift(), t.host = t.hostname);
  }
  return g = g || t.host && _.length, g && !R && _.unshift(""), _.length > 0 ? t.pathname = _.join("/") : (t.pathname = null, t.path = null), (t.pathname !== null || t.search !== null) && (t.path = (t.pathname ? t.pathname : "") + (t.search ? t.search : "")), t.auth = r.auth || t.auth, t.slashes = t.slashes || r.slashes, t.href = t.format(), t;
};
fi.prototype.parseHost = function() {
  var r = this.host, e = wE.exec(r);
  e && (e = e[0], e !== ":" && (this.port = e.substr(1)), r = r.substr(0, r.length - e.length)), r && (this.hostname = r);
};
var Yr = hd, VE = UE, x1 = { exports: {} }, Cl = { exports: {} }, uu;
function WE() {
  return uu || (uu = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function() {
        if (typeof ArrayBuffer == "function") {
          var i = t, s = i.lib, n = s.WordArray, a = n.init, o = n.init = function(c) {
            if (c instanceof ArrayBuffer && (c = new Uint8Array(c)), (c instanceof Int8Array || typeof Uint8ClampedArray < "u" && c instanceof Uint8ClampedArray || c instanceof Int16Array || c instanceof Uint16Array || c instanceof Int32Array || c instanceof Uint32Array || c instanceof Float32Array || c instanceof Float64Array) && (c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength)), c instanceof Uint8Array) {
              for (var l = c.byteLength, d = [], h = 0; h < l; h++)
                d[h >>> 2] |= c[h] << 24 - h % 4 * 8;
              a.call(this, d, l);
            } else
              a.apply(this, arguments);
          };
          o.prototype = n;
        }
      }(), t.lib.WordArray;
    });
  }(Cl)), Cl.exports;
}
var Rl = { exports: {} }, fu;
function HE() {
  return fu || (fu = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = i.enc;
        a.Utf16 = a.Utf16BE = {
          /**
           * Converts a word array to a UTF-16 BE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 BE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
           */
          stringify: function(c) {
            for (var l = c.words, d = c.sigBytes, h = [], u = 0; u < d; u += 2) {
              var f = l[u >>> 2] >>> 16 - u % 4 * 8 & 65535;
              h.push(String.fromCharCode(f));
            }
            return h.join("");
          },
          /**
           * Converts a UTF-16 BE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 BE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
           */
          parse: function(c) {
            for (var l = c.length, d = [], h = 0; h < l; h++)
              d[h >>> 1] |= c.charCodeAt(h) << 16 - h % 2 * 16;
            return n.create(d, l * 2);
          }
        }, a.Utf16LE = {
          /**
           * Converts a word array to a UTF-16 LE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 LE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
           */
          stringify: function(c) {
            for (var l = c.words, d = c.sigBytes, h = [], u = 0; u < d; u += 2) {
              var f = o(l[u >>> 2] >>> 16 - u % 4 * 8 & 65535);
              h.push(String.fromCharCode(f));
            }
            return h.join("");
          },
          /**
           * Converts a UTF-16 LE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 LE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
           */
          parse: function(c) {
            for (var l = c.length, d = [], h = 0; h < l; h++)
              d[h >>> 1] |= o(c.charCodeAt(h) << 16 - h % 2 * 16);
            return n.create(d, l * 2);
          }
        };
        function o(c) {
          return c << 8 & 4278255360 | c >>> 8 & 16711935;
        }
      }(), t.enc.Utf16;
    });
  }(Rl)), Rl.exports;
}
var Il = { exports: {} }, pu;
function ZE() {
  return pu || (pu = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = i.enc;
        a.Base64url = {
          /**
           * Converts a word array to a Base64url string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {string} The Base64url string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
           */
          stringify: function(c, l) {
            l === void 0 && (l = !0);
            var d = c.words, h = c.sigBytes, u = l ? this._safe_map : this._map;
            c.clamp();
            for (var f = [], p = 0; p < h; p += 3)
              for (var m = d[p >>> 2] >>> 24 - p % 4 * 8 & 255, g = d[p + 1 >>> 2] >>> 24 - (p + 1) % 4 * 8 & 255, x = d[p + 2 >>> 2] >>> 24 - (p + 2) % 4 * 8 & 255, _ = m << 16 | g << 8 | x, v = 0; v < 4 && p + v * 0.75 < h; v++)
                f.push(u.charAt(_ >>> 6 * (3 - v) & 63));
            var E = u.charAt(64);
            if (E)
              for (; f.length % 4; )
                f.push(E);
            return f.join("");
          },
          /**
           * Converts a Base64url string to a word array.
           *
           * @param {string} base64Str The Base64url string.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64url.parse(base64String);
           */
          parse: function(c, l) {
            l === void 0 && (l = !0);
            var d = c.length, h = l ? this._safe_map : this._map, u = this._reverseMap;
            if (!u) {
              u = this._reverseMap = [];
              for (var f = 0; f < h.length; f++)
                u[h.charCodeAt(f)] = f;
            }
            var p = h.charAt(64);
            if (p) {
              var m = c.indexOf(p);
              m !== -1 && (d = m);
            }
            return o(c, d, u);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
          _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
        };
        function o(c, l, d) {
          for (var h = [], u = 0, f = 0; f < l; f++)
            if (f % 4) {
              var p = d[c.charCodeAt(f - 1)] << f % 4 * 2, m = d[c.charCodeAt(f)] >>> 6 - f % 4 * 2, g = p | m;
              h[u >>> 2] |= g << 24 - u % 4 * 8, u++;
            }
          return n.create(h, u);
        }
      }(), t.enc.Base64url;
    });
  }(Il)), Il.exports;
}
var Ll = { exports: {} }, mu;
function ud() {
  return mu || (mu = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      return function(i) {
        var s = t, n = s.lib, a = n.WordArray, o = n.Hasher, c = s.algo, l = [], d = [];
        (function() {
          function f(x) {
            for (var _ = i.sqrt(x), v = 2; v <= _; v++)
              if (!(x % v))
                return !1;
            return !0;
          }
          function p(x) {
            return (x - (x | 0)) * 4294967296 | 0;
          }
          for (var m = 2, g = 0; g < 64; )
            f(m) && (g < 8 && (l[g] = p(i.pow(m, 1 / 2))), d[g] = p(i.pow(m, 1 / 3)), g++), m++;
        })();
        var h = [], u = c.SHA256 = o.extend({
          _doReset: function() {
            this._hash = new a.init(l.slice(0));
          },
          _doProcessBlock: function(f, p) {
            for (var m = this._hash.words, g = m[0], x = m[1], _ = m[2], v = m[3], E = m[4], b = m[5], A = m[6], C = m[7], I = 0; I < 64; I++) {
              if (I < 16)
                h[I] = f[p + I] | 0;
              else {
                var L = h[I - 15], R = (L << 25 | L >>> 7) ^ (L << 14 | L >>> 18) ^ L >>> 3, D = h[I - 2], M = (D << 15 | D >>> 17) ^ (D << 13 | D >>> 19) ^ D >>> 10;
                h[I] = R + h[I - 7] + M + h[I - 16];
              }
              var w = E & b ^ ~E & A, N = g & x ^ g & _ ^ x & _, H = (g << 30 | g >>> 2) ^ (g << 19 | g >>> 13) ^ (g << 10 | g >>> 22), G = (E << 26 | E >>> 6) ^ (E << 21 | E >>> 11) ^ (E << 7 | E >>> 25), Z = C + G + w + d[I] + h[I], $ = H + N;
              C = A, A = b, b = E, E = v + Z | 0, v = _, _ = x, x = g, g = Z + $ | 0;
            }
            m[0] = m[0] + g | 0, m[1] = m[1] + x | 0, m[2] = m[2] + _ | 0, m[3] = m[3] + v | 0, m[4] = m[4] + E | 0, m[5] = m[5] + b | 0, m[6] = m[6] + A | 0, m[7] = m[7] + C | 0;
          },
          _doFinalize: function() {
            var f = this._data, p = f.words, m = this._nDataBytes * 8, g = f.sigBytes * 8;
            return p[g >>> 5] |= 128 << 24 - g % 32, p[(g + 64 >>> 9 << 4) + 14] = i.floor(m / 4294967296), p[(g + 64 >>> 9 << 4) + 15] = m, f.sigBytes = p.length * 4, this._process(), this._hash;
          },
          clone: function() {
            var f = o.clone.call(this);
            return f._hash = this._hash.clone(), f;
          }
        });
        s.SHA256 = o._createHelper(u), s.HmacSHA256 = o._createHmacHelper(u);
      }(Math), t.SHA256;
    });
  }(Ll)), Ll.exports;
}
var Dl = { exports: {} }, gu;
function $E() {
  return gu || (gu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ud());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = i.algo, o = a.SHA256, c = a.SHA224 = o.extend({
          _doReset: function() {
            this._hash = new n.init([
              3238371032,
              914150663,
              812702999,
              4144912697,
              4290775857,
              1750603025,
              1694076839,
              3204075428
            ]);
          },
          _doFinalize: function() {
            var l = o._doFinalize.call(this);
            return l.sigBytes -= 4, l;
          }
        });
        i.SHA224 = o._createHelper(c), i.HmacSHA224 = o._createHmacHelper(c);
      }(), t.SHA224;
    });
  }(Dl)), Dl.exports;
}
var Pl = { exports: {} }, _u;
function v1() {
  return _u || (_u = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Cn());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.Hasher, a = i.x64, o = a.Word, c = a.WordArray, l = i.algo;
        function d() {
          return o.create.apply(o, arguments);
        }
        var h = [
          d(1116352408, 3609767458),
          d(1899447441, 602891725),
          d(3049323471, 3964484399),
          d(3921009573, 2173295548),
          d(961987163, 4081628472),
          d(1508970993, 3053834265),
          d(2453635748, 2937671579),
          d(2870763221, 3664609560),
          d(3624381080, 2734883394),
          d(310598401, 1164996542),
          d(607225278, 1323610764),
          d(1426881987, 3590304994),
          d(1925078388, 4068182383),
          d(2162078206, 991336113),
          d(2614888103, 633803317),
          d(3248222580, 3479774868),
          d(3835390401, 2666613458),
          d(4022224774, 944711139),
          d(264347078, 2341262773),
          d(604807628, 2007800933),
          d(770255983, 1495990901),
          d(1249150122, 1856431235),
          d(1555081692, 3175218132),
          d(1996064986, 2198950837),
          d(2554220882, 3999719339),
          d(2821834349, 766784016),
          d(2952996808, 2566594879),
          d(3210313671, 3203337956),
          d(3336571891, 1034457026),
          d(3584528711, 2466948901),
          d(113926993, 3758326383),
          d(338241895, 168717936),
          d(666307205, 1188179964),
          d(773529912, 1546045734),
          d(1294757372, 1522805485),
          d(1396182291, 2643833823),
          d(1695183700, 2343527390),
          d(1986661051, 1014477480),
          d(2177026350, 1206759142),
          d(2456956037, 344077627),
          d(2730485921, 1290863460),
          d(2820302411, 3158454273),
          d(3259730800, 3505952657),
          d(3345764771, 106217008),
          d(3516065817, 3606008344),
          d(3600352804, 1432725776),
          d(4094571909, 1467031594),
          d(275423344, 851169720),
          d(430227734, 3100823752),
          d(506948616, 1363258195),
          d(659060556, 3750685593),
          d(883997877, 3785050280),
          d(958139571, 3318307427),
          d(1322822218, 3812723403),
          d(1537002063, 2003034995),
          d(1747873779, 3602036899),
          d(1955562222, 1575990012),
          d(2024104815, 1125592928),
          d(2227730452, 2716904306),
          d(2361852424, 442776044),
          d(2428436474, 593698344),
          d(2756734187, 3733110249),
          d(3204031479, 2999351573),
          d(3329325298, 3815920427),
          d(3391569614, 3928383900),
          d(3515267271, 566280711),
          d(3940187606, 3454069534),
          d(4118630271, 4000239992),
          d(116418474, 1914138554),
          d(174292421, 2731055270),
          d(289380356, 3203993006),
          d(460393269, 320620315),
          d(685471733, 587496836),
          d(852142971, 1086792851),
          d(1017036298, 365543100),
          d(1126000580, 2618297676),
          d(1288033470, 3409855158),
          d(1501505948, 4234509866),
          d(1607167915, 987167468),
          d(1816402316, 1246189591)
        ], u = [];
        (function() {
          for (var p = 0; p < 80; p++)
            u[p] = d();
        })();
        var f = l.SHA512 = n.extend({
          _doReset: function() {
            this._hash = new c.init([
              new o.init(1779033703, 4089235720),
              new o.init(3144134277, 2227873595),
              new o.init(1013904242, 4271175723),
              new o.init(2773480762, 1595750129),
              new o.init(1359893119, 2917565137),
              new o.init(2600822924, 725511199),
              new o.init(528734635, 4215389547),
              new o.init(1541459225, 327033209)
            ]);
          },
          _doProcessBlock: function(p, m) {
            for (var g = this._hash.words, x = g[0], _ = g[1], v = g[2], E = g[3], b = g[4], A = g[5], C = g[6], I = g[7], L = x.high, R = x.low, D = _.high, M = _.low, w = v.high, N = v.low, H = E.high, G = E.low, Z = b.high, $ = b.low, Y = A.high, W = A.low, k = C.high, P = C.low, B = I.high, O = I.low, j = L, Q = R, ne = D, J = M, Se = w, Ce = N, Te = H, Xe = G, be = Z, Re = $, mt = Y, ee = W, xe = k, Ee = P, tt = B, Ie = O, Ve = 0; Ve < 80; Ve++) {
              var ke, Rt, Et = u[Ve];
              if (Ve < 16)
                Rt = Et.high = p[m + Ve * 2] | 0, ke = Et.low = p[m + Ve * 2 + 1] | 0;
              else {
                var Fi = u[Ve - 15], lt = Fi.high, ei = Fi.low, js = (lt >>> 1 | ei << 31) ^ (lt >>> 8 | ei << 24) ^ lt >>> 7, es = (ei >>> 1 | lt << 31) ^ (ei >>> 8 | lt << 24) ^ (ei >>> 7 | lt << 25), Oi = u[Ve - 2], St = Oi.high, ti = Oi.low, Ty = (St >>> 19 | ti << 13) ^ (St << 3 | ti >>> 29) ^ St >>> 6, ch = (ti >>> 19 | St << 13) ^ (ti << 3 | St >>> 29) ^ (ti >>> 6 | St << 26), dh = u[Ve - 7], by = dh.high, Ay = dh.low, hh = u[Ve - 16], Cy = hh.high, uh = hh.low;
                ke = es + Ay, Rt = js + by + (ke >>> 0 < es >>> 0 ? 1 : 0), ke = ke + ch, Rt = Rt + Ty + (ke >>> 0 < ch >>> 0 ? 1 : 0), ke = ke + uh, Rt = Rt + Cy + (ke >>> 0 < uh >>> 0 ? 1 : 0), Et.high = Rt, Et.low = ke;
              }
              var Ry = be & mt ^ ~be & xe, fh = Re & ee ^ ~Re & Ee, Iy = j & ne ^ j & Se ^ ne & Se, Ly = Q & J ^ Q & Ce ^ J & Ce, Dy = (j >>> 28 | Q << 4) ^ (j << 30 | Q >>> 2) ^ (j << 25 | Q >>> 7), ph = (Q >>> 28 | j << 4) ^ (Q << 30 | j >>> 2) ^ (Q << 25 | j >>> 7), Py = (be >>> 14 | Re << 18) ^ (be >>> 18 | Re << 14) ^ (be << 23 | Re >>> 9), ky = (Re >>> 14 | be << 18) ^ (Re >>> 18 | be << 14) ^ (Re << 23 | be >>> 9), mh = h[Ve], wy = mh.high, gh = mh.low, Nt = Ie + ky, ts = tt + Py + (Nt >>> 0 < Ie >>> 0 ? 1 : 0), Nt = Nt + fh, ts = ts + Ry + (Nt >>> 0 < fh >>> 0 ? 1 : 0), Nt = Nt + gh, ts = ts + wy + (Nt >>> 0 < gh >>> 0 ? 1 : 0), Nt = Nt + ke, ts = ts + Rt + (Nt >>> 0 < ke >>> 0 ? 1 : 0), _h = ph + Ly, My = Dy + Iy + (_h >>> 0 < ph >>> 0 ? 1 : 0);
              tt = xe, Ie = Ee, xe = mt, Ee = ee, mt = be, ee = Re, Re = Xe + Nt | 0, be = Te + ts + (Re >>> 0 < Xe >>> 0 ? 1 : 0) | 0, Te = Se, Xe = Ce, Se = ne, Ce = J, ne = j, J = Q, Q = Nt + _h | 0, j = ts + My + (Q >>> 0 < Nt >>> 0 ? 1 : 0) | 0;
            }
            R = x.low = R + Q, x.high = L + j + (R >>> 0 < Q >>> 0 ? 1 : 0), M = _.low = M + J, _.high = D + ne + (M >>> 0 < J >>> 0 ? 1 : 0), N = v.low = N + Ce, v.high = w + Se + (N >>> 0 < Ce >>> 0 ? 1 : 0), G = E.low = G + Xe, E.high = H + Te + (G >>> 0 < Xe >>> 0 ? 1 : 0), $ = b.low = $ + Re, b.high = Z + be + ($ >>> 0 < Re >>> 0 ? 1 : 0), W = A.low = W + ee, A.high = Y + mt + (W >>> 0 < ee >>> 0 ? 1 : 0), P = C.low = P + Ee, C.high = k + xe + (P >>> 0 < Ee >>> 0 ? 1 : 0), O = I.low = O + Ie, I.high = B + tt + (O >>> 0 < Ie >>> 0 ? 1 : 0);
          },
          _doFinalize: function() {
            var p = this._data, m = p.words, g = this._nDataBytes * 8, x = p.sigBytes * 8;
            m[x >>> 5] |= 128 << 24 - x % 32, m[(x + 128 >>> 10 << 5) + 30] = Math.floor(g / 4294967296), m[(x + 128 >>> 10 << 5) + 31] = g, p.sigBytes = m.length * 4, this._process();
            var _ = this._hash.toX32();
            return _;
          },
          clone: function() {
            var p = n.clone.call(this);
            return p._hash = this._hash.clone(), p;
          },
          blockSize: 1024 / 32
        });
        i.SHA512 = n._createHelper(f), i.HmacSHA512 = n._createHmacHelper(f);
      }(), t.SHA512;
    });
  }(Pl)), Pl.exports;
}
var kl = { exports: {} }, yu;
function KE() {
  return yu || (yu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Cn(), v1());
    })(le, function(t) {
      return function() {
        var i = t, s = i.x64, n = s.Word, a = s.WordArray, o = i.algo, c = o.SHA512, l = o.SHA384 = c.extend({
          _doReset: function() {
            this._hash = new a.init([
              new n.init(3418070365, 3238371032),
              new n.init(1654270250, 914150663),
              new n.init(2438529370, 812702999),
              new n.init(355462360, 4144912697),
              new n.init(1731405415, 4290775857),
              new n.init(2394180231, 1750603025),
              new n.init(3675008525, 1694076839),
              new n.init(1203062813, 3204075428)
            ]);
          },
          _doFinalize: function() {
            var d = c._doFinalize.call(this);
            return d.sigBytes -= 16, d;
          }
        });
        i.SHA384 = c._createHelper(l), i.HmacSHA384 = c._createHmacHelper(l);
      }(), t.SHA384;
    });
  }(kl)), kl.exports;
}
var wl = { exports: {} }, xu;
function XE() {
  return xu || (xu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Cn());
    })(le, function(t) {
      return function(i) {
        var s = t, n = s.lib, a = n.WordArray, o = n.Hasher, c = s.x64, l = c.Word, d = s.algo, h = [], u = [], f = [];
        (function() {
          for (var g = 1, x = 0, _ = 0; _ < 24; _++) {
            h[g + 5 * x] = (_ + 1) * (_ + 2) / 2 % 64;
            var v = x % 5, E = (2 * g + 3 * x) % 5;
            g = v, x = E;
          }
          for (var g = 0; g < 5; g++)
            for (var x = 0; x < 5; x++)
              u[g + 5 * x] = x + (2 * g + 3 * x) % 5 * 5;
          for (var b = 1, A = 0; A < 24; A++) {
            for (var C = 0, I = 0, L = 0; L < 7; L++) {
              if (b & 1) {
                var R = (1 << L) - 1;
                R < 32 ? I ^= 1 << R : C ^= 1 << R - 32;
              }
              b & 128 ? b = b << 1 ^ 113 : b <<= 1;
            }
            f[A] = l.create(C, I);
          }
        })();
        var p = [];
        (function() {
          for (var g = 0; g < 25; g++)
            p[g] = l.create();
        })();
        var m = d.SHA3 = o.extend({
          /**
           * Configuration options.
           *
           * @property {number} outputLength
           *   The desired number of bits in the output hash.
           *   Only values permitted are: 224, 256, 384, 512.
           *   Default: 512
           */
          cfg: o.cfg.extend({
            outputLength: 512
          }),
          _doReset: function() {
            for (var g = this._state = [], x = 0; x < 25; x++)
              g[x] = new l.init();
            this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
          },
          _doProcessBlock: function(g, x) {
            for (var _ = this._state, v = this.blockSize / 2, E = 0; E < v; E++) {
              var b = g[x + 2 * E], A = g[x + 2 * E + 1];
              b = (b << 8 | b >>> 24) & 16711935 | (b << 24 | b >>> 8) & 4278255360, A = (A << 8 | A >>> 24) & 16711935 | (A << 24 | A >>> 8) & 4278255360;
              var C = _[E];
              C.high ^= A, C.low ^= b;
            }
            for (var I = 0; I < 24; I++) {
              for (var L = 0; L < 5; L++) {
                for (var R = 0, D = 0, M = 0; M < 5; M++) {
                  var C = _[L + 5 * M];
                  R ^= C.high, D ^= C.low;
                }
                var w = p[L];
                w.high = R, w.low = D;
              }
              for (var L = 0; L < 5; L++)
                for (var N = p[(L + 4) % 5], H = p[(L + 1) % 5], G = H.high, Z = H.low, R = N.high ^ (G << 1 | Z >>> 31), D = N.low ^ (Z << 1 | G >>> 31), M = 0; M < 5; M++) {
                  var C = _[L + 5 * M];
                  C.high ^= R, C.low ^= D;
                }
              for (var $ = 1; $ < 25; $++) {
                var R, D, C = _[$], Y = C.high, W = C.low, k = h[$];
                k < 32 ? (R = Y << k | W >>> 32 - k, D = W << k | Y >>> 32 - k) : (R = W << k - 32 | Y >>> 64 - k, D = Y << k - 32 | W >>> 64 - k);
                var P = p[u[$]];
                P.high = R, P.low = D;
              }
              var B = p[0], O = _[0];
              B.high = O.high, B.low = O.low;
              for (var L = 0; L < 5; L++)
                for (var M = 0; M < 5; M++) {
                  var $ = L + 5 * M, C = _[$], j = p[$], Q = p[(L + 1) % 5 + 5 * M], ne = p[(L + 2) % 5 + 5 * M];
                  C.high = j.high ^ ~Q.high & ne.high, C.low = j.low ^ ~Q.low & ne.low;
                }
              var C = _[0], J = f[I];
              C.high ^= J.high, C.low ^= J.low;
            }
          },
          _doFinalize: function() {
            var g = this._data, x = g.words;
            this._nDataBytes * 8;
            var _ = g.sigBytes * 8, v = this.blockSize * 32;
            x[_ >>> 5] |= 1 << 24 - _ % 32, x[(i.ceil((_ + 1) / v) * v >>> 5) - 1] |= 128, g.sigBytes = x.length * 4, this._process();
            for (var E = this._state, b = this.cfg.outputLength / 8, A = b / 8, C = [], I = 0; I < A; I++) {
              var L = E[I], R = L.high, D = L.low;
              R = (R << 8 | R >>> 24) & 16711935 | (R << 24 | R >>> 8) & 4278255360, D = (D << 8 | D >>> 24) & 16711935 | (D << 24 | D >>> 8) & 4278255360, C.push(D), C.push(R);
            }
            return new a.init(C, b);
          },
          clone: function() {
            for (var g = o.clone.call(this), x = g._state = this._state.slice(0), _ = 0; _ < 25; _++)
              x[_] = x[_].clone();
            return g;
          }
        });
        s.SHA3 = o._createHelper(m), s.HmacSHA3 = o._createHmacHelper(m);
      }(Math), t.SHA3;
    });
  }(wl)), wl.exports;
}
var Ml = { exports: {} }, vu;
function YE() {
  return vu || (vu = 1, function(r, e) {
    (function(t, i) {
      r.exports = i(ge());
    })(le, function(t) {
      /** @preserve
      			(c) 2012 by Cédric Mesnil. All rights reserved.
      
      			Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      			    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      			    - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      			THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      			*/
      return function(i) {
        var s = t, n = s.lib, a = n.WordArray, o = n.Hasher, c = s.algo, l = a.create([
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11,
          12,
          13,
          14,
          15,
          7,
          4,
          13,
          1,
          10,
          6,
          15,
          3,
          12,
          0,
          9,
          5,
          2,
          14,
          11,
          8,
          3,
          10,
          14,
          4,
          9,
          15,
          8,
          1,
          2,
          7,
          0,
          6,
          13,
          11,
          5,
          12,
          1,
          9,
          11,
          10,
          0,
          8,
          12,
          4,
          13,
          3,
          7,
          15,
          14,
          5,
          6,
          2,
          4,
          0,
          5,
          9,
          7,
          12,
          2,
          10,
          14,
          1,
          3,
          8,
          11,
          6,
          15,
          13
        ]), d = a.create([
          5,
          14,
          7,
          0,
          9,
          2,
          11,
          4,
          13,
          6,
          15,
          8,
          1,
          10,
          3,
          12,
          6,
          11,
          3,
          7,
          0,
          13,
          5,
          10,
          14,
          15,
          8,
          12,
          4,
          9,
          1,
          2,
          15,
          5,
          1,
          3,
          7,
          14,
          6,
          9,
          11,
          8,
          12,
          2,
          10,
          0,
          4,
          13,
          8,
          6,
          4,
          1,
          3,
          11,
          15,
          0,
          5,
          12,
          2,
          13,
          9,
          7,
          10,
          14,
          12,
          15,
          10,
          4,
          1,
          5,
          8,
          7,
          6,
          2,
          13,
          14,
          0,
          3,
          9,
          11
        ]), h = a.create([
          11,
          14,
          15,
          12,
          5,
          8,
          7,
          9,
          11,
          13,
          14,
          15,
          6,
          7,
          9,
          8,
          7,
          6,
          8,
          13,
          11,
          9,
          7,
          15,
          7,
          12,
          15,
          9,
          11,
          7,
          13,
          12,
          11,
          13,
          6,
          7,
          14,
          9,
          13,
          15,
          14,
          8,
          13,
          6,
          5,
          12,
          7,
          5,
          11,
          12,
          14,
          15,
          14,
          15,
          9,
          8,
          9,
          14,
          5,
          6,
          8,
          6,
          5,
          12,
          9,
          15,
          5,
          11,
          6,
          8,
          13,
          12,
          5,
          12,
          13,
          14,
          11,
          8,
          5,
          6
        ]), u = a.create([
          8,
          9,
          9,
          11,
          13,
          15,
          15,
          5,
          7,
          7,
          8,
          11,
          14,
          14,
          12,
          6,
          9,
          13,
          15,
          7,
          12,
          8,
          9,
          11,
          7,
          7,
          12,
          7,
          6,
          15,
          13,
          11,
          9,
          7,
          15,
          11,
          8,
          6,
          6,
          14,
          12,
          13,
          5,
          14,
          13,
          13,
          7,
          5,
          15,
          5,
          8,
          11,
          14,
          14,
          6,
          14,
          6,
          9,
          12,
          9,
          12,
          5,
          15,
          8,
          8,
          5,
          12,
          9,
          12,
          5,
          14,
          6,
          8,
          13,
          6,
          5,
          15,
          13,
          11,
          11
        ]), f = a.create([0, 1518500249, 1859775393, 2400959708, 2840853838]), p = a.create([1352829926, 1548603684, 1836072691, 2053994217, 0]), m = c.RIPEMD160 = o.extend({
          _doReset: function() {
            this._hash = a.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
          },
          _doProcessBlock: function(A, C) {
            for (var I = 0; I < 16; I++) {
              var L = C + I, R = A[L];
              A[L] = (R << 8 | R >>> 24) & 16711935 | (R << 24 | R >>> 8) & 4278255360;
            }
            var D = this._hash.words, M = f.words, w = p.words, N = l.words, H = d.words, G = h.words, Z = u.words, $, Y, W, k, P, B, O, j, Q, ne;
            B = $ = D[0], O = Y = D[1], j = W = D[2], Q = k = D[3], ne = P = D[4];
            for (var J, I = 0; I < 80; I += 1)
              J = $ + A[C + N[I]] | 0, I < 16 ? J += g(Y, W, k) + M[0] : I < 32 ? J += x(Y, W, k) + M[1] : I < 48 ? J += _(Y, W, k) + M[2] : I < 64 ? J += v(Y, W, k) + M[3] : J += E(Y, W, k) + M[4], J = J | 0, J = b(J, G[I]), J = J + P | 0, $ = P, P = k, k = b(W, 10), W = Y, Y = J, J = B + A[C + H[I]] | 0, I < 16 ? J += E(O, j, Q) + w[0] : I < 32 ? J += v(O, j, Q) + w[1] : I < 48 ? J += _(O, j, Q) + w[2] : I < 64 ? J += x(O, j, Q) + w[3] : J += g(O, j, Q) + w[4], J = J | 0, J = b(J, Z[I]), J = J + ne | 0, B = ne, ne = Q, Q = b(j, 10), j = O, O = J;
            J = D[1] + W + Q | 0, D[1] = D[2] + k + ne | 0, D[2] = D[3] + P + B | 0, D[3] = D[4] + $ + O | 0, D[4] = D[0] + Y + j | 0, D[0] = J;
          },
          _doFinalize: function() {
            var A = this._data, C = A.words, I = this._nDataBytes * 8, L = A.sigBytes * 8;
            C[L >>> 5] |= 128 << 24 - L % 32, C[(L + 64 >>> 9 << 4) + 14] = (I << 8 | I >>> 24) & 16711935 | (I << 24 | I >>> 8) & 4278255360, A.sigBytes = (C.length + 1) * 4, this._process();
            for (var R = this._hash, D = R.words, M = 0; M < 5; M++) {
              var w = D[M];
              D[M] = (w << 8 | w >>> 24) & 16711935 | (w << 24 | w >>> 8) & 4278255360;
            }
            return R;
          },
          clone: function() {
            var A = o.clone.call(this);
            return A._hash = this._hash.clone(), A;
          }
        });
        function g(A, C, I) {
          return A ^ C ^ I;
        }
        function x(A, C, I) {
          return A & C | ~A & I;
        }
        function _(A, C, I) {
          return (A | ~C) ^ I;
        }
        function v(A, C, I) {
          return A & I | C & ~I;
        }
        function E(A, C, I) {
          return A ^ (C | ~I);
        }
        function b(A, C) {
          return A << C | A >>> 32 - C;
        }
        s.RIPEMD160 = o._createHelper(m), s.HmacRIPEMD160 = o._createHmacHelper(m);
      }(), t.RIPEMD160;
    });
  }(Ml)), Ml.exports;
}
var Bl = { exports: {} }, Eu;
function zE() {
  return Eu || (Eu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ud(), td());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.Base, a = s.WordArray, o = i.algo, c = o.SHA256, l = o.HMAC, d = o.PBKDF2 = n.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hasher to use. Default: SHA256
           * @property {number} iterations The number of iterations to perform. Default: 250000
           */
          cfg: n.extend({
            keySize: 128 / 32,
            hasher: c,
            iterations: 25e4
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.PBKDF2.create();
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
           */
          init: function(h) {
            this.cfg = this.cfg.extend(h);
          },
          /**
           * Computes the Password-Based Key Derivation Function 2.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(h, u) {
            for (var f = this.cfg, p = l.create(f.hasher, h), m = a.create(), g = a.create([1]), x = m.words, _ = g.words, v = f.keySize, E = f.iterations; x.length < v; ) {
              var b = p.update(u).finalize(g);
              p.reset();
              for (var A = b.words, C = A.length, I = b, L = 1; L < E; L++) {
                I = p.finalize(I), p.reset();
                for (var R = I.words, D = 0; D < C; D++)
                  A[D] ^= R[D];
              }
              m.concat(b), _[0]++;
            }
            return m.sigBytes = v * 4, m;
          }
        });
        i.PBKDF2 = function(h, u, f) {
          return d.create(f).compute(h, u);
        };
      }(), t.PBKDF2;
    });
  }(Bl)), Bl.exports;
}
var Fl = { exports: {} }, Su;
function jE() {
  return Su || (Su = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.mode.CFB = function() {
        var i = t.lib.BlockCipherMode.extend();
        i.Encryptor = i.extend({
          processBlock: function(n, a) {
            var o = this._cipher, c = o.blockSize;
            s.call(this, n, a, c, o), this._prevBlock = n.slice(a, a + c);
          }
        }), i.Decryptor = i.extend({
          processBlock: function(n, a) {
            var o = this._cipher, c = o.blockSize, l = n.slice(a, a + c);
            s.call(this, n, a, c, o), this._prevBlock = l;
          }
        });
        function s(n, a, o, c) {
          var l, d = this._iv;
          d ? (l = d.slice(0), this._iv = void 0) : l = this._prevBlock, c.encryptBlock(l, 0);
          for (var h = 0; h < o; h++)
            n[a + h] ^= l[h];
        }
        return i;
      }(), t.mode.CFB;
    });
  }(Fl)), Fl.exports;
}
var Ol = { exports: {} }, Tu;
function QE() {
  return Tu || (Tu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.mode.CTR = function() {
        var i = t.lib.BlockCipherMode.extend(), s = i.Encryptor = i.extend({
          processBlock: function(n, a) {
            var o = this._cipher, c = o.blockSize, l = this._iv, d = this._counter;
            l && (d = this._counter = l.slice(0), this._iv = void 0);
            var h = d.slice(0);
            o.encryptBlock(h, 0), d[c - 1] = d[c - 1] + 1 | 0;
            for (var u = 0; u < c; u++)
              n[a + u] ^= h[u];
          }
        });
        return i.Decryptor = s, i;
      }(), t.mode.CTR;
    });
  }(Ol)), Ol.exports;
}
var Nl = { exports: {} }, bu;
function JE() {
  return bu || (bu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      /** @preserve
       * Counter block mode compatible with  Dr Brian Gladman fileenc.c
       * derived from CryptoJS.mode.CTR
       * Jan Hruby jhruby.web@gmail.com
       */
      return t.mode.CTRGladman = function() {
        var i = t.lib.BlockCipherMode.extend();
        function s(o) {
          if ((o >> 24 & 255) === 255) {
            var c = o >> 16 & 255, l = o >> 8 & 255, d = o & 255;
            c === 255 ? (c = 0, l === 255 ? (l = 0, d === 255 ? d = 0 : ++d) : ++l) : ++c, o = 0, o += c << 16, o += l << 8, o += d;
          } else
            o += 1 << 24;
          return o;
        }
        function n(o) {
          return (o[0] = s(o[0])) === 0 && (o[1] = s(o[1])), o;
        }
        var a = i.Encryptor = i.extend({
          processBlock: function(o, c) {
            var l = this._cipher, d = l.blockSize, h = this._iv, u = this._counter;
            h && (u = this._counter = h.slice(0), this._iv = void 0), n(u);
            var f = u.slice(0);
            l.encryptBlock(f, 0);
            for (var p = 0; p < d; p++)
              o[c + p] ^= f[p];
          }
        });
        return i.Decryptor = a, i;
      }(), t.mode.CTRGladman;
    });
  }(Nl)), Nl.exports;
}
var Gl = { exports: {} }, Au;
function qE() {
  return Au || (Au = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.mode.OFB = function() {
        var i = t.lib.BlockCipherMode.extend(), s = i.Encryptor = i.extend({
          processBlock: function(n, a) {
            var o = this._cipher, c = o.blockSize, l = this._iv, d = this._keystream;
            l && (d = this._keystream = l.slice(0), this._iv = void 0), o.encryptBlock(d, 0);
            for (var h = 0; h < c; h++)
              n[a + h] ^= d[h];
          }
        });
        return i.Decryptor = s, i;
      }(), t.mode.OFB;
    });
  }(Gl)), Gl.exports;
}
var Ul = { exports: {} }, Cu;
function eS() {
  return Cu || (Cu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.mode.ECB = function() {
        var i = t.lib.BlockCipherMode.extend();
        return i.Encryptor = i.extend({
          processBlock: function(s, n) {
            this._cipher.encryptBlock(s, n);
          }
        }), i.Decryptor = i.extend({
          processBlock: function(s, n) {
            this._cipher.decryptBlock(s, n);
          }
        }), i;
      }(), t.mode.ECB;
    });
  }(Ul)), Ul.exports;
}
var Vl = { exports: {} }, Ru;
function tS() {
  return Ru || (Ru = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.pad.AnsiX923 = {
        pad: function(i, s) {
          var n = i.sigBytes, a = s * 4, o = a - n % a, c = n + o - 1;
          i.clamp(), i.words[c >>> 2] |= o << 24 - c % 4 * 8, i.sigBytes += o;
        },
        unpad: function(i) {
          var s = i.words[i.sigBytes - 1 >>> 2] & 255;
          i.sigBytes -= s;
        }
      }, t.pad.Ansix923;
    });
  }(Vl)), Vl.exports;
}
var Wl = { exports: {} }, Iu;
function iS() {
  return Iu || (Iu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.pad.Iso10126 = {
        pad: function(i, s) {
          var n = s * 4, a = n - i.sigBytes % n;
          i.concat(t.lib.WordArray.random(a - 1)).concat(t.lib.WordArray.create([a << 24], 1));
        },
        unpad: function(i) {
          var s = i.words[i.sigBytes - 1 >>> 2] & 255;
          i.sigBytes -= s;
        }
      }, t.pad.Iso10126;
    });
  }(Wl)), Wl.exports;
}
var Hl = { exports: {} }, Lu;
function sS() {
  return Lu || (Lu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.pad.Iso97971 = {
        pad: function(i, s) {
          i.concat(t.lib.WordArray.create([2147483648], 1)), t.pad.ZeroPadding.pad(i, s);
        },
        unpad: function(i) {
          t.pad.ZeroPadding.unpad(i), i.sigBytes--;
        }
      }, t.pad.Iso97971;
    });
  }(Hl)), Hl.exports;
}
var Zl = { exports: {} }, Du;
function rS() {
  return Du || (Du = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.pad.ZeroPadding = {
        pad: function(i, s) {
          var n = s * 4;
          i.clamp(), i.sigBytes += n - (i.sigBytes % n || n);
        },
        unpad: function(i) {
          for (var s = i.words, n = i.sigBytes - 1, n = i.sigBytes - 1; n >= 0; n--)
            if (s[n >>> 2] >>> 24 - n % 4 * 8 & 255) {
              i.sigBytes = n + 1;
              break;
            }
        }
      }, t.pad.ZeroPadding;
    });
  }(Zl)), Zl.exports;
}
var $l = { exports: {} }, Pu;
function nS() {
  return Pu || (Pu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return t.pad.NoPadding = {
        pad: function() {
        },
        unpad: function() {
        }
      }, t.pad.NoPadding;
    });
  }($l)), $l.exports;
}
var Kl = { exports: {} }, ku;
function aS() {
  return ku || (ku = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), ot());
    })(le, function(t) {
      return function(i) {
        var s = t, n = s.lib, a = n.CipherParams, o = s.enc, c = o.Hex, l = s.format;
        l.Hex = {
          /**
           * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The hexadecimally encoded string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.format.Hex.stringify(cipherParams);
           */
          stringify: function(d) {
            return d.ciphertext.toString(c);
          },
          /**
           * Converts a hexadecimally encoded ciphertext string to a cipher params object.
           *
           * @param {string} input The hexadecimally encoded string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.Hex.parse(hexString);
           */
          parse: function(d) {
            var h = c.parse(d);
            return a.create({ ciphertext: h });
          }
        };
      }(), t.format.Hex;
    });
  }(Kl)), Kl.exports;
}
var Xl = { exports: {} }, wu;
function oS() {
  return wu || (wu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.WordArray, a = s.BlockCipher, o = i.algo, c = [
          57,
          49,
          41,
          33,
          25,
          17,
          9,
          1,
          58,
          50,
          42,
          34,
          26,
          18,
          10,
          2,
          59,
          51,
          43,
          35,
          27,
          19,
          11,
          3,
          60,
          52,
          44,
          36,
          63,
          55,
          47,
          39,
          31,
          23,
          15,
          7,
          62,
          54,
          46,
          38,
          30,
          22,
          14,
          6,
          61,
          53,
          45,
          37,
          29,
          21,
          13,
          5,
          28,
          20,
          12,
          4
        ], l = [
          14,
          17,
          11,
          24,
          1,
          5,
          3,
          28,
          15,
          6,
          21,
          10,
          23,
          19,
          12,
          4,
          26,
          8,
          16,
          7,
          27,
          20,
          13,
          2,
          41,
          52,
          31,
          37,
          47,
          55,
          30,
          40,
          51,
          45,
          33,
          48,
          44,
          49,
          39,
          56,
          34,
          53,
          46,
          42,
          50,
          36,
          29,
          32
        ], d = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28], h = [
          {
            0: 8421888,
            268435456: 32768,
            536870912: 8421378,
            805306368: 2,
            1073741824: 512,
            1342177280: 8421890,
            1610612736: 8389122,
            1879048192: 8388608,
            2147483648: 514,
            2415919104: 8389120,
            2684354560: 33280,
            2952790016: 8421376,
            3221225472: 32770,
            3489660928: 8388610,
            3758096384: 0,
            4026531840: 33282,
            134217728: 0,
            402653184: 8421890,
            671088640: 33282,
            939524096: 32768,
            1207959552: 8421888,
            1476395008: 512,
            1744830464: 8421378,
            2013265920: 2,
            2281701376: 8389120,
            2550136832: 33280,
            2818572288: 8421376,
            3087007744: 8389122,
            3355443200: 8388610,
            3623878656: 32770,
            3892314112: 514,
            4160749568: 8388608,
            1: 32768,
            268435457: 2,
            536870913: 8421888,
            805306369: 8388608,
            1073741825: 8421378,
            1342177281: 33280,
            1610612737: 512,
            1879048193: 8389122,
            2147483649: 8421890,
            2415919105: 8421376,
            2684354561: 8388610,
            2952790017: 33282,
            3221225473: 514,
            3489660929: 8389120,
            3758096385: 32770,
            4026531841: 0,
            134217729: 8421890,
            402653185: 8421376,
            671088641: 8388608,
            939524097: 512,
            1207959553: 32768,
            1476395009: 8388610,
            1744830465: 2,
            2013265921: 33282,
            2281701377: 32770,
            2550136833: 8389122,
            2818572289: 514,
            3087007745: 8421888,
            3355443201: 8389120,
            3623878657: 0,
            3892314113: 33280,
            4160749569: 8421378
          },
          {
            0: 1074282512,
            16777216: 16384,
            33554432: 524288,
            50331648: 1074266128,
            67108864: 1073741840,
            83886080: 1074282496,
            100663296: 1073758208,
            117440512: 16,
            134217728: 540672,
            150994944: 1073758224,
            167772160: 1073741824,
            184549376: 540688,
            201326592: 524304,
            218103808: 0,
            234881024: 16400,
            251658240: 1074266112,
            8388608: 1073758208,
            25165824: 540688,
            41943040: 16,
            58720256: 1073758224,
            75497472: 1074282512,
            92274688: 1073741824,
            109051904: 524288,
            125829120: 1074266128,
            142606336: 524304,
            159383552: 0,
            176160768: 16384,
            192937984: 1074266112,
            209715200: 1073741840,
            226492416: 540672,
            243269632: 1074282496,
            260046848: 16400,
            268435456: 0,
            285212672: 1074266128,
            301989888: 1073758224,
            318767104: 1074282496,
            335544320: 1074266112,
            352321536: 16,
            369098752: 540688,
            385875968: 16384,
            402653184: 16400,
            419430400: 524288,
            436207616: 524304,
            452984832: 1073741840,
            469762048: 540672,
            486539264: 1073758208,
            503316480: 1073741824,
            520093696: 1074282512,
            276824064: 540688,
            293601280: 524288,
            310378496: 1074266112,
            327155712: 16384,
            343932928: 1073758208,
            360710144: 1074282512,
            377487360: 16,
            394264576: 1073741824,
            411041792: 1074282496,
            427819008: 1073741840,
            444596224: 1073758224,
            461373440: 524304,
            478150656: 0,
            494927872: 16400,
            511705088: 1074266128,
            528482304: 540672
          },
          {
            0: 260,
            1048576: 0,
            2097152: 67109120,
            3145728: 65796,
            4194304: 65540,
            5242880: 67108868,
            6291456: 67174660,
            7340032: 67174400,
            8388608: 67108864,
            9437184: 67174656,
            10485760: 65792,
            11534336: 67174404,
            12582912: 67109124,
            13631488: 65536,
            14680064: 4,
            15728640: 256,
            524288: 67174656,
            1572864: 67174404,
            2621440: 0,
            3670016: 67109120,
            4718592: 67108868,
            5767168: 65536,
            6815744: 65540,
            7864320: 260,
            8912896: 4,
            9961472: 256,
            11010048: 67174400,
            12058624: 65796,
            13107200: 65792,
            14155776: 67109124,
            15204352: 67174660,
            16252928: 67108864,
            16777216: 67174656,
            17825792: 65540,
            18874368: 65536,
            19922944: 67109120,
            20971520: 256,
            22020096: 67174660,
            23068672: 67108868,
            24117248: 0,
            25165824: 67109124,
            26214400: 67108864,
            27262976: 4,
            28311552: 65792,
            29360128: 67174400,
            30408704: 260,
            31457280: 65796,
            32505856: 67174404,
            17301504: 67108864,
            18350080: 260,
            19398656: 67174656,
            20447232: 0,
            21495808: 65540,
            22544384: 67109120,
            23592960: 256,
            24641536: 67174404,
            25690112: 65536,
            26738688: 67174660,
            27787264: 65796,
            28835840: 67108868,
            29884416: 67109124,
            30932992: 67174400,
            31981568: 4,
            33030144: 65792
          },
          {
            0: 2151682048,
            65536: 2147487808,
            131072: 4198464,
            196608: 2151677952,
            262144: 0,
            327680: 4198400,
            393216: 2147483712,
            458752: 4194368,
            524288: 2147483648,
            589824: 4194304,
            655360: 64,
            720896: 2147487744,
            786432: 2151678016,
            851968: 4160,
            917504: 4096,
            983040: 2151682112,
            32768: 2147487808,
            98304: 64,
            163840: 2151678016,
            229376: 2147487744,
            294912: 4198400,
            360448: 2151682112,
            425984: 0,
            491520: 2151677952,
            557056: 4096,
            622592: 2151682048,
            688128: 4194304,
            753664: 4160,
            819200: 2147483648,
            884736: 4194368,
            950272: 4198464,
            1015808: 2147483712,
            1048576: 4194368,
            1114112: 4198400,
            1179648: 2147483712,
            1245184: 0,
            1310720: 4160,
            1376256: 2151678016,
            1441792: 2151682048,
            1507328: 2147487808,
            1572864: 2151682112,
            1638400: 2147483648,
            1703936: 2151677952,
            1769472: 4198464,
            1835008: 2147487744,
            1900544: 4194304,
            1966080: 64,
            2031616: 4096,
            1081344: 2151677952,
            1146880: 2151682112,
            1212416: 0,
            1277952: 4198400,
            1343488: 4194368,
            1409024: 2147483648,
            1474560: 2147487808,
            1540096: 64,
            1605632: 2147483712,
            1671168: 4096,
            1736704: 2147487744,
            1802240: 2151678016,
            1867776: 4160,
            1933312: 2151682048,
            1998848: 4194304,
            2064384: 4198464
          },
          {
            0: 128,
            4096: 17039360,
            8192: 262144,
            12288: 536870912,
            16384: 537133184,
            20480: 16777344,
            24576: 553648256,
            28672: 262272,
            32768: 16777216,
            36864: 537133056,
            40960: 536871040,
            45056: 553910400,
            49152: 553910272,
            53248: 0,
            57344: 17039488,
            61440: 553648128,
            2048: 17039488,
            6144: 553648256,
            10240: 128,
            14336: 17039360,
            18432: 262144,
            22528: 537133184,
            26624: 553910272,
            30720: 536870912,
            34816: 537133056,
            38912: 0,
            43008: 553910400,
            47104: 16777344,
            51200: 536871040,
            55296: 553648128,
            59392: 16777216,
            63488: 262272,
            65536: 262144,
            69632: 128,
            73728: 536870912,
            77824: 553648256,
            81920: 16777344,
            86016: 553910272,
            90112: 537133184,
            94208: 16777216,
            98304: 553910400,
            102400: 553648128,
            106496: 17039360,
            110592: 537133056,
            114688: 262272,
            118784: 536871040,
            122880: 0,
            126976: 17039488,
            67584: 553648256,
            71680: 16777216,
            75776: 17039360,
            79872: 537133184,
            83968: 536870912,
            88064: 17039488,
            92160: 128,
            96256: 553910272,
            100352: 262272,
            104448: 553910400,
            108544: 0,
            112640: 553648128,
            116736: 16777344,
            120832: 262144,
            124928: 537133056,
            129024: 536871040
          },
          {
            0: 268435464,
            256: 8192,
            512: 270532608,
            768: 270540808,
            1024: 268443648,
            1280: 2097152,
            1536: 2097160,
            1792: 268435456,
            2048: 0,
            2304: 268443656,
            2560: 2105344,
            2816: 8,
            3072: 270532616,
            3328: 2105352,
            3584: 8200,
            3840: 270540800,
            128: 270532608,
            384: 270540808,
            640: 8,
            896: 2097152,
            1152: 2105352,
            1408: 268435464,
            1664: 268443648,
            1920: 8200,
            2176: 2097160,
            2432: 8192,
            2688: 268443656,
            2944: 270532616,
            3200: 0,
            3456: 270540800,
            3712: 2105344,
            3968: 268435456,
            4096: 268443648,
            4352: 270532616,
            4608: 270540808,
            4864: 8200,
            5120: 2097152,
            5376: 268435456,
            5632: 268435464,
            5888: 2105344,
            6144: 2105352,
            6400: 0,
            6656: 8,
            6912: 270532608,
            7168: 8192,
            7424: 268443656,
            7680: 270540800,
            7936: 2097160,
            4224: 8,
            4480: 2105344,
            4736: 2097152,
            4992: 268435464,
            5248: 268443648,
            5504: 8200,
            5760: 270540808,
            6016: 270532608,
            6272: 270540800,
            6528: 270532616,
            6784: 8192,
            7040: 2105352,
            7296: 2097160,
            7552: 0,
            7808: 268435456,
            8064: 268443656
          },
          {
            0: 1048576,
            16: 33555457,
            32: 1024,
            48: 1049601,
            64: 34604033,
            80: 0,
            96: 1,
            112: 34603009,
            128: 33555456,
            144: 1048577,
            160: 33554433,
            176: 34604032,
            192: 34603008,
            208: 1025,
            224: 1049600,
            240: 33554432,
            8: 34603009,
            24: 0,
            40: 33555457,
            56: 34604032,
            72: 1048576,
            88: 33554433,
            104: 33554432,
            120: 1025,
            136: 1049601,
            152: 33555456,
            168: 34603008,
            184: 1048577,
            200: 1024,
            216: 34604033,
            232: 1,
            248: 1049600,
            256: 33554432,
            272: 1048576,
            288: 33555457,
            304: 34603009,
            320: 1048577,
            336: 33555456,
            352: 34604032,
            368: 1049601,
            384: 1025,
            400: 34604033,
            416: 1049600,
            432: 1,
            448: 0,
            464: 34603008,
            480: 33554433,
            496: 1024,
            264: 1049600,
            280: 33555457,
            296: 34603009,
            312: 1,
            328: 33554432,
            344: 1048576,
            360: 1025,
            376: 34604032,
            392: 33554433,
            408: 34603008,
            424: 0,
            440: 34604033,
            456: 1049601,
            472: 1024,
            488: 33555456,
            504: 1048577
          },
          {
            0: 134219808,
            1: 131072,
            2: 134217728,
            3: 32,
            4: 131104,
            5: 134350880,
            6: 134350848,
            7: 2048,
            8: 134348800,
            9: 134219776,
            10: 133120,
            11: 134348832,
            12: 2080,
            13: 0,
            14: 134217760,
            15: 133152,
            2147483648: 2048,
            2147483649: 134350880,
            2147483650: 134219808,
            2147483651: 134217728,
            2147483652: 134348800,
            2147483653: 133120,
            2147483654: 133152,
            2147483655: 32,
            2147483656: 134217760,
            2147483657: 2080,
            2147483658: 131104,
            2147483659: 134350848,
            2147483660: 0,
            2147483661: 134348832,
            2147483662: 134219776,
            2147483663: 131072,
            16: 133152,
            17: 134350848,
            18: 32,
            19: 2048,
            20: 134219776,
            21: 134217760,
            22: 134348832,
            23: 131072,
            24: 0,
            25: 131104,
            26: 134348800,
            27: 134219808,
            28: 134350880,
            29: 133120,
            30: 2080,
            31: 134217728,
            2147483664: 131072,
            2147483665: 2048,
            2147483666: 134348832,
            2147483667: 133152,
            2147483668: 32,
            2147483669: 134348800,
            2147483670: 134217728,
            2147483671: 134219808,
            2147483672: 134350880,
            2147483673: 134217760,
            2147483674: 134219776,
            2147483675: 0,
            2147483676: 133120,
            2147483677: 2080,
            2147483678: 131104,
            2147483679: 134350848
          }
        ], u = [
          4160749569,
          528482304,
          33030144,
          2064384,
          129024,
          8064,
          504,
          2147483679
        ], f = o.DES = a.extend({
          _doReset: function() {
            for (var x = this._key, _ = x.words, v = [], E = 0; E < 56; E++) {
              var b = c[E] - 1;
              v[E] = _[b >>> 5] >>> 31 - b % 32 & 1;
            }
            for (var A = this._subKeys = [], C = 0; C < 16; C++) {
              for (var I = A[C] = [], L = d[C], E = 0; E < 24; E++)
                I[E / 6 | 0] |= v[(l[E] - 1 + L) % 28] << 31 - E % 6, I[4 + (E / 6 | 0)] |= v[28 + (l[E + 24] - 1 + L) % 28] << 31 - E % 6;
              I[0] = I[0] << 1 | I[0] >>> 31;
              for (var E = 1; E < 7; E++)
                I[E] = I[E] >>> (E - 1) * 4 + 3;
              I[7] = I[7] << 5 | I[7] >>> 27;
            }
            for (var R = this._invSubKeys = [], E = 0; E < 16; E++)
              R[E] = A[15 - E];
          },
          encryptBlock: function(x, _) {
            this._doCryptBlock(x, _, this._subKeys);
          },
          decryptBlock: function(x, _) {
            this._doCryptBlock(x, _, this._invSubKeys);
          },
          _doCryptBlock: function(x, _, v) {
            this._lBlock = x[_], this._rBlock = x[_ + 1], p.call(this, 4, 252645135), p.call(this, 16, 65535), m.call(this, 2, 858993459), m.call(this, 8, 16711935), p.call(this, 1, 1431655765);
            for (var E = 0; E < 16; E++) {
              for (var b = v[E], A = this._lBlock, C = this._rBlock, I = 0, L = 0; L < 8; L++)
                I |= h[L][((C ^ b[L]) & u[L]) >>> 0];
              this._lBlock = C, this._rBlock = A ^ I;
            }
            var R = this._lBlock;
            this._lBlock = this._rBlock, this._rBlock = R, p.call(this, 1, 1431655765), m.call(this, 8, 16711935), m.call(this, 2, 858993459), p.call(this, 16, 65535), p.call(this, 4, 252645135), x[_] = this._lBlock, x[_ + 1] = this._rBlock;
          },
          keySize: 64 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        function p(x, _) {
          var v = (this._lBlock >>> x ^ this._rBlock) & _;
          this._rBlock ^= v, this._lBlock ^= v << x;
        }
        function m(x, _) {
          var v = (this._rBlock >>> x ^ this._lBlock) & _;
          this._lBlock ^= v, this._rBlock ^= v << x;
        }
        i.DES = a._createHelper(f);
        var g = o.TripleDES = a.extend({
          _doReset: function() {
            var x = this._key, _ = x.words;
            if (_.length !== 2 && _.length !== 4 && _.length < 6)
              throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");
            var v = _.slice(0, 2), E = _.length < 4 ? _.slice(0, 2) : _.slice(2, 4), b = _.length < 6 ? _.slice(0, 2) : _.slice(4, 6);
            this._des1 = f.createEncryptor(n.create(v)), this._des2 = f.createEncryptor(n.create(E)), this._des3 = f.createEncryptor(n.create(b));
          },
          encryptBlock: function(x, _) {
            this._des1.encryptBlock(x, _), this._des2.decryptBlock(x, _), this._des3.encryptBlock(x, _);
          },
          decryptBlock: function(x, _) {
            this._des3.decryptBlock(x, _), this._des2.encryptBlock(x, _), this._des1.decryptBlock(x, _);
          },
          keySize: 192 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        i.TripleDES = a._createHelper(g);
      }(), t.TripleDES;
    });
  }(Xl)), Xl.exports;
}
var Yl = { exports: {} }, Mu;
function lS() {
  return Mu || (Mu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.StreamCipher, a = i.algo, o = a.RC4 = n.extend({
          _doReset: function() {
            for (var d = this._key, h = d.words, u = d.sigBytes, f = this._S = [], p = 0; p < 256; p++)
              f[p] = p;
            for (var p = 0, m = 0; p < 256; p++) {
              var g = p % u, x = h[g >>> 2] >>> 24 - g % 4 * 8 & 255;
              m = (m + f[p] + x) % 256;
              var _ = f[p];
              f[p] = f[m], f[m] = _;
            }
            this._i = this._j = 0;
          },
          _doProcessBlock: function(d, h) {
            d[h] ^= c.call(this);
          },
          keySize: 256 / 32,
          ivSize: 0
        });
        function c() {
          for (var d = this._S, h = this._i, u = this._j, f = 0, p = 0; p < 4; p++) {
            h = (h + 1) % 256, u = (u + d[h]) % 256;
            var m = d[h];
            d[h] = d[u], d[u] = m, f |= d[(d[h] + d[u]) % 256] << 24 - p * 8;
          }
          return this._i = h, this._j = u, f;
        }
        i.RC4 = n._createHelper(o);
        var l = a.RC4Drop = o.extend({
          /**
           * Configuration options.
           *
           * @property {number} drop The number of keystream words to drop. Default 192
           */
          cfg: o.cfg.extend({
            drop: 192
          }),
          _doReset: function() {
            o._doReset.call(this);
            for (var d = this.cfg.drop; d > 0; d--)
              c.call(this);
          }
        });
        i.RC4Drop = n._createHelper(l);
      }(), t.RC4;
    });
  }(Yl)), Yl.exports;
}
var zl = { exports: {} }, Bu;
function cS() {
  return Bu || (Bu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.StreamCipher, a = i.algo, o = [], c = [], l = [], d = a.Rabbit = n.extend({
          _doReset: function() {
            for (var u = this._key.words, f = this.cfg.iv, p = 0; p < 4; p++)
              u[p] = (u[p] << 8 | u[p] >>> 24) & 16711935 | (u[p] << 24 | u[p] >>> 8) & 4278255360;
            var m = this._X = [
              u[0],
              u[3] << 16 | u[2] >>> 16,
              u[1],
              u[0] << 16 | u[3] >>> 16,
              u[2],
              u[1] << 16 | u[0] >>> 16,
              u[3],
              u[2] << 16 | u[1] >>> 16
            ], g = this._C = [
              u[2] << 16 | u[2] >>> 16,
              u[0] & 4294901760 | u[1] & 65535,
              u[3] << 16 | u[3] >>> 16,
              u[1] & 4294901760 | u[2] & 65535,
              u[0] << 16 | u[0] >>> 16,
              u[2] & 4294901760 | u[3] & 65535,
              u[1] << 16 | u[1] >>> 16,
              u[3] & 4294901760 | u[0] & 65535
            ];
            this._b = 0;
            for (var p = 0; p < 4; p++)
              h.call(this);
            for (var p = 0; p < 8; p++)
              g[p] ^= m[p + 4 & 7];
            if (f) {
              var x = f.words, _ = x[0], v = x[1], E = (_ << 8 | _ >>> 24) & 16711935 | (_ << 24 | _ >>> 8) & 4278255360, b = (v << 8 | v >>> 24) & 16711935 | (v << 24 | v >>> 8) & 4278255360, A = E >>> 16 | b & 4294901760, C = b << 16 | E & 65535;
              g[0] ^= E, g[1] ^= A, g[2] ^= b, g[3] ^= C, g[4] ^= E, g[5] ^= A, g[6] ^= b, g[7] ^= C;
              for (var p = 0; p < 4; p++)
                h.call(this);
            }
          },
          _doProcessBlock: function(u, f) {
            var p = this._X;
            h.call(this), o[0] = p[0] ^ p[5] >>> 16 ^ p[3] << 16, o[1] = p[2] ^ p[7] >>> 16 ^ p[5] << 16, o[2] = p[4] ^ p[1] >>> 16 ^ p[7] << 16, o[3] = p[6] ^ p[3] >>> 16 ^ p[1] << 16;
            for (var m = 0; m < 4; m++)
              o[m] = (o[m] << 8 | o[m] >>> 24) & 16711935 | (o[m] << 24 | o[m] >>> 8) & 4278255360, u[f + m] ^= o[m];
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function h() {
          for (var u = this._X, f = this._C, p = 0; p < 8; p++)
            c[p] = f[p];
          f[0] = f[0] + 1295307597 + this._b | 0, f[1] = f[1] + 3545052371 + (f[0] >>> 0 < c[0] >>> 0 ? 1 : 0) | 0, f[2] = f[2] + 886263092 + (f[1] >>> 0 < c[1] >>> 0 ? 1 : 0) | 0, f[3] = f[3] + 1295307597 + (f[2] >>> 0 < c[2] >>> 0 ? 1 : 0) | 0, f[4] = f[4] + 3545052371 + (f[3] >>> 0 < c[3] >>> 0 ? 1 : 0) | 0, f[5] = f[5] + 886263092 + (f[4] >>> 0 < c[4] >>> 0 ? 1 : 0) | 0, f[6] = f[6] + 1295307597 + (f[5] >>> 0 < c[5] >>> 0 ? 1 : 0) | 0, f[7] = f[7] + 3545052371 + (f[6] >>> 0 < c[6] >>> 0 ? 1 : 0) | 0, this._b = f[7] >>> 0 < c[7] >>> 0 ? 1 : 0;
          for (var p = 0; p < 8; p++) {
            var m = u[p] + f[p], g = m & 65535, x = m >>> 16, _ = ((g * g >>> 17) + g * x >>> 15) + x * x, v = ((m & 4294901760) * m | 0) + ((m & 65535) * m | 0);
            l[p] = _ ^ v;
          }
          u[0] = l[0] + (l[7] << 16 | l[7] >>> 16) + (l[6] << 16 | l[6] >>> 16) | 0, u[1] = l[1] + (l[0] << 8 | l[0] >>> 24) + l[7] | 0, u[2] = l[2] + (l[1] << 16 | l[1] >>> 16) + (l[0] << 16 | l[0] >>> 16) | 0, u[3] = l[3] + (l[2] << 8 | l[2] >>> 24) + l[1] | 0, u[4] = l[4] + (l[3] << 16 | l[3] >>> 16) + (l[2] << 16 | l[2] >>> 16) | 0, u[5] = l[5] + (l[4] << 8 | l[4] >>> 24) + l[3] | 0, u[6] = l[6] + (l[5] << 16 | l[5] >>> 16) + (l[4] << 16 | l[4] >>> 16) | 0, u[7] = l[7] + (l[6] << 8 | l[6] >>> 24) + l[5] | 0;
        }
        i.Rabbit = n._createHelper(d);
      }(), t.Rabbit;
    });
  }(zl)), zl.exports;
}
var jl = { exports: {} }, Fu;
function dS() {
  return Fu || (Fu = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.StreamCipher, a = i.algo, o = [], c = [], l = [], d = a.RabbitLegacy = n.extend({
          _doReset: function() {
            var u = this._key.words, f = this.cfg.iv, p = this._X = [
              u[0],
              u[3] << 16 | u[2] >>> 16,
              u[1],
              u[0] << 16 | u[3] >>> 16,
              u[2],
              u[1] << 16 | u[0] >>> 16,
              u[3],
              u[2] << 16 | u[1] >>> 16
            ], m = this._C = [
              u[2] << 16 | u[2] >>> 16,
              u[0] & 4294901760 | u[1] & 65535,
              u[3] << 16 | u[3] >>> 16,
              u[1] & 4294901760 | u[2] & 65535,
              u[0] << 16 | u[0] >>> 16,
              u[2] & 4294901760 | u[3] & 65535,
              u[1] << 16 | u[1] >>> 16,
              u[3] & 4294901760 | u[0] & 65535
            ];
            this._b = 0;
            for (var g = 0; g < 4; g++)
              h.call(this);
            for (var g = 0; g < 8; g++)
              m[g] ^= p[g + 4 & 7];
            if (f) {
              var x = f.words, _ = x[0], v = x[1], E = (_ << 8 | _ >>> 24) & 16711935 | (_ << 24 | _ >>> 8) & 4278255360, b = (v << 8 | v >>> 24) & 16711935 | (v << 24 | v >>> 8) & 4278255360, A = E >>> 16 | b & 4294901760, C = b << 16 | E & 65535;
              m[0] ^= E, m[1] ^= A, m[2] ^= b, m[3] ^= C, m[4] ^= E, m[5] ^= A, m[6] ^= b, m[7] ^= C;
              for (var g = 0; g < 4; g++)
                h.call(this);
            }
          },
          _doProcessBlock: function(u, f) {
            var p = this._X;
            h.call(this), o[0] = p[0] ^ p[5] >>> 16 ^ p[3] << 16, o[1] = p[2] ^ p[7] >>> 16 ^ p[5] << 16, o[2] = p[4] ^ p[1] >>> 16 ^ p[7] << 16, o[3] = p[6] ^ p[3] >>> 16 ^ p[1] << 16;
            for (var m = 0; m < 4; m++)
              o[m] = (o[m] << 8 | o[m] >>> 24) & 16711935 | (o[m] << 24 | o[m] >>> 8) & 4278255360, u[f + m] ^= o[m];
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function h() {
          for (var u = this._X, f = this._C, p = 0; p < 8; p++)
            c[p] = f[p];
          f[0] = f[0] + 1295307597 + this._b | 0, f[1] = f[1] + 3545052371 + (f[0] >>> 0 < c[0] >>> 0 ? 1 : 0) | 0, f[2] = f[2] + 886263092 + (f[1] >>> 0 < c[1] >>> 0 ? 1 : 0) | 0, f[3] = f[3] + 1295307597 + (f[2] >>> 0 < c[2] >>> 0 ? 1 : 0) | 0, f[4] = f[4] + 3545052371 + (f[3] >>> 0 < c[3] >>> 0 ? 1 : 0) | 0, f[5] = f[5] + 886263092 + (f[4] >>> 0 < c[4] >>> 0 ? 1 : 0) | 0, f[6] = f[6] + 1295307597 + (f[5] >>> 0 < c[5] >>> 0 ? 1 : 0) | 0, f[7] = f[7] + 3545052371 + (f[6] >>> 0 < c[6] >>> 0 ? 1 : 0) | 0, this._b = f[7] >>> 0 < c[7] >>> 0 ? 1 : 0;
          for (var p = 0; p < 8; p++) {
            var m = u[p] + f[p], g = m & 65535, x = m >>> 16, _ = ((g * g >>> 17) + g * x >>> 15) + x * x, v = ((m & 4294901760) * m | 0) + ((m & 65535) * m | 0);
            l[p] = _ ^ v;
          }
          u[0] = l[0] + (l[7] << 16 | l[7] >>> 16) + (l[6] << 16 | l[6] >>> 16) | 0, u[1] = l[1] + (l[0] << 8 | l[0] >>> 24) + l[7] | 0, u[2] = l[2] + (l[1] << 16 | l[1] >>> 16) + (l[0] << 16 | l[0] >>> 16) | 0, u[3] = l[3] + (l[2] << 8 | l[2] >>> 24) + l[1] | 0, u[4] = l[4] + (l[3] << 16 | l[3] >>> 16) + (l[2] << 16 | l[2] >>> 16) | 0, u[5] = l[5] + (l[4] << 8 | l[4] >>> 24) + l[3] | 0, u[6] = l[6] + (l[5] << 16 | l[5] >>> 16) + (l[4] << 16 | l[4] >>> 16) | 0, u[7] = l[7] + (l[6] << 8 | l[6] >>> 24) + l[5] | 0;
        }
        i.RabbitLegacy = n._createHelper(d);
      }(), t.RabbitLegacy;
    });
  }(jl)), jl.exports;
}
var Ql = { exports: {} }, Ou;
function hS() {
  return Ou || (Ou = 1, function(r, e) {
    (function(t, i, s) {
      r.exports = i(ge(), Zs(), $s(), Es(), ot());
    })(le, function(t) {
      return function() {
        var i = t, s = i.lib, n = s.BlockCipher, a = i.algo;
        const o = 16, c = [
          608135816,
          2242054355,
          320440878,
          57701188,
          2752067618,
          698298832,
          137296536,
          3964562569,
          1160258022,
          953160567,
          3193202383,
          887688300,
          3232508343,
          3380367581,
          1065670069,
          3041331479,
          2450970073,
          2306472731
        ], l = [
          [
            3509652390,
            2564797868,
            805139163,
            3491422135,
            3101798381,
            1780907670,
            3128725573,
            4046225305,
            614570311,
            3012652279,
            134345442,
            2240740374,
            1667834072,
            1901547113,
            2757295779,
            4103290238,
            227898511,
            1921955416,
            1904987480,
            2182433518,
            2069144605,
            3260701109,
            2620446009,
            720527379,
            3318853667,
            677414384,
            3393288472,
            3101374703,
            2390351024,
            1614419982,
            1822297739,
            2954791486,
            3608508353,
            3174124327,
            2024746970,
            1432378464,
            3864339955,
            2857741204,
            1464375394,
            1676153920,
            1439316330,
            715854006,
            3033291828,
            289532110,
            2706671279,
            2087905683,
            3018724369,
            1668267050,
            732546397,
            1947742710,
            3462151702,
            2609353502,
            2950085171,
            1814351708,
            2050118529,
            680887927,
            999245976,
            1800124847,
            3300911131,
            1713906067,
            1641548236,
            4213287313,
            1216130144,
            1575780402,
            4018429277,
            3917837745,
            3693486850,
            3949271944,
            596196993,
            3549867205,
            258830323,
            2213823033,
            772490370,
            2760122372,
            1774776394,
            2652871518,
            566650946,
            4142492826,
            1728879713,
            2882767088,
            1783734482,
            3629395816,
            2517608232,
            2874225571,
            1861159788,
            326777828,
            3124490320,
            2130389656,
            2716951837,
            967770486,
            1724537150,
            2185432712,
            2364442137,
            1164943284,
            2105845187,
            998989502,
            3765401048,
            2244026483,
            1075463327,
            1455516326,
            1322494562,
            910128902,
            469688178,
            1117454909,
            936433444,
            3490320968,
            3675253459,
            1240580251,
            122909385,
            2157517691,
            634681816,
            4142456567,
            3825094682,
            3061402683,
            2540495037,
            79693498,
            3249098678,
            1084186820,
            1583128258,
            426386531,
            1761308591,
            1047286709,
            322548459,
            995290223,
            1845252383,
            2603652396,
            3431023940,
            2942221577,
            3202600964,
            3727903485,
            1712269319,
            422464435,
            3234572375,
            1170764815,
            3523960633,
            3117677531,
            1434042557,
            442511882,
            3600875718,
            1076654713,
            1738483198,
            4213154764,
            2393238008,
            3677496056,
            1014306527,
            4251020053,
            793779912,
            2902807211,
            842905082,
            4246964064,
            1395751752,
            1040244610,
            2656851899,
            3396308128,
            445077038,
            3742853595,
            3577915638,
            679411651,
            2892444358,
            2354009459,
            1767581616,
            3150600392,
            3791627101,
            3102740896,
            284835224,
            4246832056,
            1258075500,
            768725851,
            2589189241,
            3069724005,
            3532540348,
            1274779536,
            3789419226,
            2764799539,
            1660621633,
            3471099624,
            4011903706,
            913787905,
            3497959166,
            737222580,
            2514213453,
            2928710040,
            3937242737,
            1804850592,
            3499020752,
            2949064160,
            2386320175,
            2390070455,
            2415321851,
            4061277028,
            2290661394,
            2416832540,
            1336762016,
            1754252060,
            3520065937,
            3014181293,
            791618072,
            3188594551,
            3933548030,
            2332172193,
            3852520463,
            3043980520,
            413987798,
            3465142937,
            3030929376,
            4245938359,
            2093235073,
            3534596313,
            375366246,
            2157278981,
            2479649556,
            555357303,
            3870105701,
            2008414854,
            3344188149,
            4221384143,
            3956125452,
            2067696032,
            3594591187,
            2921233993,
            2428461,
            544322398,
            577241275,
            1471733935,
            610547355,
            4027169054,
            1432588573,
            1507829418,
            2025931657,
            3646575487,
            545086370,
            48609733,
            2200306550,
            1653985193,
            298326376,
            1316178497,
            3007786442,
            2064951626,
            458293330,
            2589141269,
            3591329599,
            3164325604,
            727753846,
            2179363840,
            146436021,
            1461446943,
            4069977195,
            705550613,
            3059967265,
            3887724982,
            4281599278,
            3313849956,
            1404054877,
            2845806497,
            146425753,
            1854211946
          ],
          [
            1266315497,
            3048417604,
            3681880366,
            3289982499,
            290971e4,
            1235738493,
            2632868024,
            2414719590,
            3970600049,
            1771706367,
            1449415276,
            3266420449,
            422970021,
            1963543593,
            2690192192,
            3826793022,
            1062508698,
            1531092325,
            1804592342,
            2583117782,
            2714934279,
            4024971509,
            1294809318,
            4028980673,
            1289560198,
            2221992742,
            1669523910,
            35572830,
            157838143,
            1052438473,
            1016535060,
            1802137761,
            1753167236,
            1386275462,
            3080475397,
            2857371447,
            1040679964,
            2145300060,
            2390574316,
            1461121720,
            2956646967,
            4031777805,
            4028374788,
            33600511,
            2920084762,
            1018524850,
            629373528,
            3691585981,
            3515945977,
            2091462646,
            2486323059,
            586499841,
            988145025,
            935516892,
            3367335476,
            2599673255,
            2839830854,
            265290510,
            3972581182,
            2759138881,
            3795373465,
            1005194799,
            847297441,
            406762289,
            1314163512,
            1332590856,
            1866599683,
            4127851711,
            750260880,
            613907577,
            1450815602,
            3165620655,
            3734664991,
            3650291728,
            3012275730,
            3704569646,
            1427272223,
            778793252,
            1343938022,
            2676280711,
            2052605720,
            1946737175,
            3164576444,
            3914038668,
            3967478842,
            3682934266,
            1661551462,
            3294938066,
            4011595847,
            840292616,
            3712170807,
            616741398,
            312560963,
            711312465,
            1351876610,
            322626781,
            1910503582,
            271666773,
            2175563734,
            1594956187,
            70604529,
            3617834859,
            1007753275,
            1495573769,
            4069517037,
            2549218298,
            2663038764,
            504708206,
            2263041392,
            3941167025,
            2249088522,
            1514023603,
            1998579484,
            1312622330,
            694541497,
            2582060303,
            2151582166,
            1382467621,
            776784248,
            2618340202,
            3323268794,
            2497899128,
            2784771155,
            503983604,
            4076293799,
            907881277,
            423175695,
            432175456,
            1378068232,
            4145222326,
            3954048622,
            3938656102,
            3820766613,
            2793130115,
            2977904593,
            26017576,
            3274890735,
            3194772133,
            1700274565,
            1756076034,
            4006520079,
            3677328699,
            720338349,
            1533947780,
            354530856,
            688349552,
            3973924725,
            1637815568,
            332179504,
            3949051286,
            53804574,
            2852348879,
            3044236432,
            1282449977,
            3583942155,
            3416972820,
            4006381244,
            1617046695,
            2628476075,
            3002303598,
            1686838959,
            431878346,
            2686675385,
            1700445008,
            1080580658,
            1009431731,
            832498133,
            3223435511,
            2605976345,
            2271191193,
            2516031870,
            1648197032,
            4164389018,
            2548247927,
            300782431,
            375919233,
            238389289,
            3353747414,
            2531188641,
            2019080857,
            1475708069,
            455242339,
            2609103871,
            448939670,
            3451063019,
            1395535956,
            2413381860,
            1841049896,
            1491858159,
            885456874,
            4264095073,
            4001119347,
            1565136089,
            3898914787,
            1108368660,
            540939232,
            1173283510,
            2745871338,
            3681308437,
            4207628240,
            3343053890,
            4016749493,
            1699691293,
            1103962373,
            3625875870,
            2256883143,
            3830138730,
            1031889488,
            3479347698,
            1535977030,
            4236805024,
            3251091107,
            2132092099,
            1774941330,
            1199868427,
            1452454533,
            157007616,
            2904115357,
            342012276,
            595725824,
            1480756522,
            206960106,
            497939518,
            591360097,
            863170706,
            2375253569,
            3596610801,
            1814182875,
            2094937945,
            3421402208,
            1082520231,
            3463918190,
            2785509508,
            435703966,
            3908032597,
            1641649973,
            2842273706,
            3305899714,
            1510255612,
            2148256476,
            2655287854,
            3276092548,
            4258621189,
            236887753,
            3681803219,
            274041037,
            1734335097,
            3815195456,
            3317970021,
            1899903192,
            1026095262,
            4050517792,
            356393447,
            2410691914,
            3873677099,
            3682840055
          ],
          [
            3913112168,
            2491498743,
            4132185628,
            2489919796,
            1091903735,
            1979897079,
            3170134830,
            3567386728,
            3557303409,
            857797738,
            1136121015,
            1342202287,
            507115054,
            2535736646,
            337727348,
            3213592640,
            1301675037,
            2528481711,
            1895095763,
            1721773893,
            3216771564,
            62756741,
            2142006736,
            835421444,
            2531993523,
            1442658625,
            3659876326,
            2882144922,
            676362277,
            1392781812,
            170690266,
            3921047035,
            1759253602,
            3611846912,
            1745797284,
            664899054,
            1329594018,
            3901205900,
            3045908486,
            2062866102,
            2865634940,
            3543621612,
            3464012697,
            1080764994,
            553557557,
            3656615353,
            3996768171,
            991055499,
            499776247,
            1265440854,
            648242737,
            3940784050,
            980351604,
            3713745714,
            1749149687,
            3396870395,
            4211799374,
            3640570775,
            1161844396,
            3125318951,
            1431517754,
            545492359,
            4268468663,
            3499529547,
            1437099964,
            2702547544,
            3433638243,
            2581715763,
            2787789398,
            1060185593,
            1593081372,
            2418618748,
            4260947970,
            69676912,
            2159744348,
            86519011,
            2512459080,
            3838209314,
            1220612927,
            3339683548,
            133810670,
            1090789135,
            1078426020,
            1569222167,
            845107691,
            3583754449,
            4072456591,
            1091646820,
            628848692,
            1613405280,
            3757631651,
            526609435,
            236106946,
            48312990,
            2942717905,
            3402727701,
            1797494240,
            859738849,
            992217954,
            4005476642,
            2243076622,
            3870952857,
            3732016268,
            765654824,
            3490871365,
            2511836413,
            1685915746,
            3888969200,
            1414112111,
            2273134842,
            3281911079,
            4080962846,
            172450625,
            2569994100,
            980381355,
            4109958455,
            2819808352,
            2716589560,
            2568741196,
            3681446669,
            3329971472,
            1835478071,
            660984891,
            3704678404,
            4045999559,
            3422617507,
            3040415634,
            1762651403,
            1719377915,
            3470491036,
            2693910283,
            3642056355,
            3138596744,
            1364962596,
            2073328063,
            1983633131,
            926494387,
            3423689081,
            2150032023,
            4096667949,
            1749200295,
            3328846651,
            309677260,
            2016342300,
            1779581495,
            3079819751,
            111262694,
            1274766160,
            443224088,
            298511866,
            1025883608,
            3806446537,
            1145181785,
            168956806,
            3641502830,
            3584813610,
            1689216846,
            3666258015,
            3200248200,
            1692713982,
            2646376535,
            4042768518,
            1618508792,
            1610833997,
            3523052358,
            4130873264,
            2001055236,
            3610705100,
            2202168115,
            4028541809,
            2961195399,
            1006657119,
            2006996926,
            3186142756,
            1430667929,
            3210227297,
            1314452623,
            4074634658,
            4101304120,
            2273951170,
            1399257539,
            3367210612,
            3027628629,
            1190975929,
            2062231137,
            2333990788,
            2221543033,
            2438960610,
            1181637006,
            548689776,
            2362791313,
            3372408396,
            3104550113,
            3145860560,
            296247880,
            1970579870,
            3078560182,
            3769228297,
            1714227617,
            3291629107,
            3898220290,
            166772364,
            1251581989,
            493813264,
            448347421,
            195405023,
            2709975567,
            677966185,
            3703036547,
            1463355134,
            2715995803,
            1338867538,
            1343315457,
            2802222074,
            2684532164,
            233230375,
            2599980071,
            2000651841,
            3277868038,
            1638401717,
            4028070440,
            3237316320,
            6314154,
            819756386,
            300326615,
            590932579,
            1405279636,
            3267499572,
            3150704214,
            2428286686,
            3959192993,
            3461946742,
            1862657033,
            1266418056,
            963775037,
            2089974820,
            2263052895,
            1917689273,
            448879540,
            3550394620,
            3981727096,
            150775221,
            3627908307,
            1303187396,
            508620638,
            2975983352,
            2726630617,
            1817252668,
            1876281319,
            1457606340,
            908771278,
            3720792119,
            3617206836,
            2455994898,
            1729034894,
            1080033504
          ],
          [
            976866871,
            3556439503,
            2881648439,
            1522871579,
            1555064734,
            1336096578,
            3548522304,
            2579274686,
            3574697629,
            3205460757,
            3593280638,
            3338716283,
            3079412587,
            564236357,
            2993598910,
            1781952180,
            1464380207,
            3163844217,
            3332601554,
            1699332808,
            1393555694,
            1183702653,
            3581086237,
            1288719814,
            691649499,
            2847557200,
            2895455976,
            3193889540,
            2717570544,
            1781354906,
            1676643554,
            2592534050,
            3230253752,
            1126444790,
            2770207658,
            2633158820,
            2210423226,
            2615765581,
            2414155088,
            3127139286,
            673620729,
            2805611233,
            1269405062,
            4015350505,
            3341807571,
            4149409754,
            1057255273,
            2012875353,
            2162469141,
            2276492801,
            2601117357,
            993977747,
            3918593370,
            2654263191,
            753973209,
            36408145,
            2530585658,
            25011837,
            3520020182,
            2088578344,
            530523599,
            2918365339,
            1524020338,
            1518925132,
            3760827505,
            3759777254,
            1202760957,
            3985898139,
            3906192525,
            674977740,
            4174734889,
            2031300136,
            2019492241,
            3983892565,
            4153806404,
            3822280332,
            352677332,
            2297720250,
            60907813,
            90501309,
            3286998549,
            1016092578,
            2535922412,
            2839152426,
            457141659,
            509813237,
            4120667899,
            652014361,
            1966332200,
            2975202805,
            55981186,
            2327461051,
            676427537,
            3255491064,
            2882294119,
            3433927263,
            1307055953,
            942726286,
            933058658,
            2468411793,
            3933900994,
            4215176142,
            1361170020,
            2001714738,
            2830558078,
            3274259782,
            1222529897,
            1679025792,
            2729314320,
            3714953764,
            1770335741,
            151462246,
            3013232138,
            1682292957,
            1483529935,
            471910574,
            1539241949,
            458788160,
            3436315007,
            1807016891,
            3718408830,
            978976581,
            1043663428,
            3165965781,
            1927990952,
            4200891579,
            2372276910,
            3208408903,
            3533431907,
            1412390302,
            2931980059,
            4132332400,
            1947078029,
            3881505623,
            4168226417,
            2941484381,
            1077988104,
            1320477388,
            886195818,
            18198404,
            3786409e3,
            2509781533,
            112762804,
            3463356488,
            1866414978,
            891333506,
            18488651,
            661792760,
            1628790961,
            3885187036,
            3141171499,
            876946877,
            2693282273,
            1372485963,
            791857591,
            2686433993,
            3759982718,
            3167212022,
            3472953795,
            2716379847,
            445679433,
            3561995674,
            3504004811,
            3574258232,
            54117162,
            3331405415,
            2381918588,
            3769707343,
            4154350007,
            1140177722,
            4074052095,
            668550556,
            3214352940,
            367459370,
            261225585,
            2610173221,
            4209349473,
            3468074219,
            3265815641,
            314222801,
            3066103646,
            3808782860,
            282218597,
            3406013506,
            3773591054,
            379116347,
            1285071038,
            846784868,
            2669647154,
            3771962079,
            3550491691,
            2305946142,
            453669953,
            1268987020,
            3317592352,
            3279303384,
            3744833421,
            2610507566,
            3859509063,
            266596637,
            3847019092,
            517658769,
            3462560207,
            3443424879,
            370717030,
            4247526661,
            2224018117,
            4143653529,
            4112773975,
            2788324899,
            2477274417,
            1456262402,
            2901442914,
            1517677493,
            1846949527,
            2295493580,
            3734397586,
            2176403920,
            1280348187,
            1908823572,
            3871786941,
            846861322,
            1172426758,
            3287448474,
            3383383037,
            1655181056,
            3139813346,
            901632758,
            1897031941,
            2986607138,
            3066810236,
            3447102507,
            1393639104,
            373351379,
            950779232,
            625454576,
            3124240540,
            4148612726,
            2007998917,
            544563296,
            2244738638,
            2330496472,
            2058025392,
            1291430526,
            424198748,
            50039436,
            29584100,
            3605783033,
            2429876329,
            2791104160,
            1057563949,
            3255363231,
            3075367218,
            3463963227,
            1469046755,
            985887462
          ]
        ];
        var d = {
          pbox: [],
          sbox: []
        };
        function h(g, x) {
          let _ = x >> 24 & 255, v = x >> 16 & 255, E = x >> 8 & 255, b = x & 255, A = g.sbox[0][_] + g.sbox[1][v];
          return A = A ^ g.sbox[2][E], A = A + g.sbox[3][b], A;
        }
        function u(g, x, _) {
          let v = x, E = _, b;
          for (let A = 0; A < o; ++A)
            v = v ^ g.pbox[A], E = h(g, v) ^ E, b = v, v = E, E = b;
          return b = v, v = E, E = b, E = E ^ g.pbox[o], v = v ^ g.pbox[o + 1], { left: v, right: E };
        }
        function f(g, x, _) {
          let v = x, E = _, b;
          for (let A = o + 1; A > 1; --A)
            v = v ^ g.pbox[A], E = h(g, v) ^ E, b = v, v = E, E = b;
          return b = v, v = E, E = b, E = E ^ g.pbox[1], v = v ^ g.pbox[0], { left: v, right: E };
        }
        function p(g, x, _) {
          for (let C = 0; C < 4; C++) {
            g.sbox[C] = [];
            for (let I = 0; I < 256; I++)
              g.sbox[C][I] = l[C][I];
          }
          let v = 0;
          for (let C = 0; C < o + 2; C++)
            g.pbox[C] = c[C] ^ x[v], v++, v >= _ && (v = 0);
          let E = 0, b = 0, A = 0;
          for (let C = 0; C < o + 2; C += 2)
            A = u(g, E, b), E = A.left, b = A.right, g.pbox[C] = E, g.pbox[C + 1] = b;
          for (let C = 0; C < 4; C++)
            for (let I = 0; I < 256; I += 2)
              A = u(g, E, b), E = A.left, b = A.right, g.sbox[C][I] = E, g.sbox[C][I + 1] = b;
          return !0;
        }
        var m = a.Blowfish = n.extend({
          _doReset: function() {
            if (this._keyPriorReset !== this._key) {
              var g = this._keyPriorReset = this._key, x = g.words, _ = g.sigBytes / 4;
              p(d, x, _);
            }
          },
          encryptBlock: function(g, x) {
            var _ = u(d, g[x], g[x + 1]);
            g[x] = _.left, g[x + 1] = _.right;
          },
          decryptBlock: function(g, x) {
            var _ = f(d, g[x], g[x + 1]);
            g[x] = _.left, g[x + 1] = _.right;
          },
          blockSize: 64 / 32,
          keySize: 128 / 32,
          ivSize: 64 / 32
        });
        i.Blowfish = n._createHelper(m);
      }(), t.Blowfish;
    });
  }(Ql)), Ql.exports;
}
(function(r, e) {
  (function(t, i, s) {
    r.exports = i(ge(), Cn(), WE(), HE(), Zs(), ZE(), $s(), Im(), ud(), $E(), v1(), KE(), XE(), YE(), td(), zE(), Es(), ot(), jE(), QE(), JE(), qE(), eS(), tS(), iS(), sS(), rS(), nS(), aS(), Lm(), oS(), lS(), cS(), dS(), hS());
  })(le, function(t) {
    return t;
  });
})(x1);
var Vn = x1.exports;
function is(r = {}) {
  let e = {}, t = Object.keys(r);
  for (let i = 0; i < t.length; i++) {
    let s = t[i];
    e[s.toLowerCase()] = r[s];
  }
  return e;
}
class uS {
  constructor() {
  }
  get(e, t = {}) {
    let i = Yr(e, !0), s = t.query || t.data;
    return s && (Object.assign(i.query, s), i.path = i.pathname + "?" + er.stringify(i.query), t.data = null, t.query = null), t.headers = is(t.headers), t.signHeaders = is(t.signHeaders), this.request("GET", i, t);
  }
  post(e, t = {}) {
    let i = Yr(e, !0), s = t.query;
    s && (Object.assign(i.query, s), i.path = i.pathname + "?" + er.stringify(i.query), t.query = null), t.headers = is(t.headers), t.signHeaders = is(t.signHeaders);
    let n = t.headers, a = n["content-type"] || n["Content-Type"];
    a || (n["content-type"] = "application/json", a = n["content-type"]);
    let o = t.data;
    return a.startsWith("application/x-www-form-urlencoded") ? t.data = er.stringify(t.data) : (a.startsWith("application/json") || !Buffer.isBuffer(t.data) && typeof t.data != "string") && (t.data = JSON.stringify(t.data)), this.request("POST", i, t, o);
  }
  put(e, t = {}) {
    let i = Yr(e, !0), s = t.query;
    s && (Object.assign(i.query, s), i.path = i.pathname + "?" + er.stringify(i.query), t.query = null), t.headers = is(t.headers), t.signHeaders = is(t.signHeaders);
    let n = t.headers, a = n["content-type"] || n["Content-Type"];
    a || (n["content-type"] = "application/json", a = n["content-type"]);
    let o = t.data;
    return a.startsWith("application/x-www-form-urlencoded") ? t.data = er.stringify(t.data) : (a.startsWith("application/json") || !Buffer.isBuffer(t.data) && typeof t.data != "string") && (t.data = JSON.stringify(t.data)), this.request("PUT", i, t, o);
  }
  delete(e, t) {
    let i = Yr(e, !0), s = t.query || t.data;
    return s && (Object.assign(i.query, s), i.path = i.pathname + "?" + er.stringify(i.query), t.data = null, t.query = null), t.headers = is(t.headers), t.signHeaders = is(t.signHeaders), this.request("DELETE", i, t);
  }
}
const Nu = "application/x-www-form-urlencoded", fS = function(r, e) {
  return Object.prototype.hasOwnProperty.call(r, e);
};
class pS extends Error {
  constructor() {
    super(...arguments);
    y(this, "code", 200);
    y(this, "data");
  }
}
const mS = "HttpClient";
class gS extends uS {
  constructor(t, i, s = "RELEASE") {
    super();
    y(this, "appKey");
    y(this, "appSecret");
    y(this, "stage");
    this.appKey = t, this.appSecret = i, this.stage = s;
  }
  buildStringToSign(t, i, s, n, a) {
    const o = `
`;
    let c = [t, o], l = i.accept;
    l && c.push(l), c.push(o);
    let d = i["content-md5"];
    d && c.push(d), c.push(o);
    let h = i["content-type"] || "";
    h && c.push(h), c.push(o);
    let u = i.date;
    u && c.push(u), c.push(o), s && (c.push(s), c.push(o));
    const f = h.startsWith(Nu) ? this.buildUrl(n, a) : this.buildUrl(n);
    return f && c.push(f), c.join("");
  }
  sign(t) {
    return Vn.HmacSHA256(t, this.appSecret).toString(Vn.enc.Base64);
  }
  md5(t) {
    return Vn.MD5(t).toString(Vn.enc.Base64);
  }
  getSignHeaderKeys(t, i) {
    let s = Object.keys(t).sort(), n = [];
    for (let a = 0; a < s.length; a++) {
      let o = s[a];
      (o.startsWith("x-ca-") || fS(i, o)) && n.push(o);
    }
    return n.sort();
  }
  buildUrl(t, i) {
    let s = Object.assign(t.query, i), n = t.pathname;
    if (Object.keys(s).length) {
      let a = Object.keys(s).sort(), o = new Array(a.length);
      for (let c = 0; c < a.length; c++) {
        let l = a[c];
        s[l] !== void 0 && s[l] !== null && "" + s[l] ? o[c] = `${l}=${s[l]}` : o[c] = `${l}`;
      }
      n += "?" + o.join("&");
    }
    return n;
  }
  buildHeaders(t = {}, i) {
    return Object.assign(
      {
        "x-ca-timestamp": Date.now(),
        "x-ca-key": this.appKey,
        "x-ca-nonce": id(),
        "x-ca-stage": this.stage,
        accept: "application/json"
      },
      t,
      i
    );
  }
  getSignedHeadersString(t, i) {
    let s = [];
    for (let n = 0; n < t.length; n++) {
      let a = t[n];
      s.push(a + ":" + i[a]);
    }
    return s.join(`
`);
  }
  async request(t, i, s, n) {
    let a = s.signHeaders, o = this.buildHeaders(s.headers, a), c = o["content-type"] || "";
    t === "POST" && !c.startsWith(Nu) && (o["content-md5"] = this.md5(s.data));
    let l = this.getSignHeaderKeys(o, a);
    o["x-ca-signature-headers"] = l.join(",");
    let d = this.getSignedHeadersString(l, o), h = typeof i == "string" ? Yr(i, !0) : i, u = this.buildStringToSign(t, o, d, h, n);
    o["x-ca-signature"] = this.sign(u), o["user-agent"] = navigator.userAgent;
    let f = await fetch(h.href, {
      method: t,
      headers: o,
      body: s.data
    }), p = f.status;
    if (p < 200 || p >= 300) {
      let x = f.headers.get("x-ca-error-message") || "", _ = new pS(`${t} ${VE(i)} failed width code(${p}). request id: ${f.headers.get("x-ca-request-id")}, error message: ${x}`);
      if (x.includes("Invalid Signature")) {
        let v = x.replace("Invalid Signature, Server StringToSign:", "");
        S.d(mS, v);
      }
      throw _.code = p, _.data = {
        headers: f.headers
      }, _;
    }
    let m = await f.text();
    return (f.headers.get("content-type") || f.headers.get("Content-Type") || "").startsWith("application/json") && (m = JSON.parse(m)), m;
  }
}
var Jl;
function _S() {
  return Jl || (Jl = new gS(re.appKey, re.appSecret)), Jl;
}
const Gu = "GatewayUtil";
function yS(r, e) {
  const t = wi.getUserToken(), i = {
    apiVer: "1.0",
    language: re.locale,
    iotToken: "",
    clientUniqueKey: Rn()
  };
  if (e)
    if (t) i.iotToken = t;
    else
      throw sd(new go("token is empty")), "token is empty";
  return {
    id: id(),
    version: "1.0",
    request: i,
    params: r
  };
}
async function zr(r, e, t, i = 1, s, n) {
  const a = Date.now();
  s = s ?? Je.gatewayProtocol, n = n ?? Je.gatewayDomain;
  const o = s + "://" + n + e, l = await new Promise(function(u, f) {
    E1(
      r,
      e,
      (p, m) => {
        if (m) return f(m);
        u(p);
      },
      t,
      s,
      n
    );
  }), d = l.code, h = d != 200;
  if (d == Bm && (sd(new go(l.message || l.msg || d.toString())), i = 0), i > 1 && h)
    return i--, zr(r, e, t, i, s, n);
  if (h)
    throw S.e(Gu, `request api url=${o} take ${Date.now() - a}ms`, t, l), l;
  return S.i(Gu, `request api url=${o} take ${Date.now() - a}ms`, t, l), l;
}
function E1(r, e, t, i, s, n) {
  const a = _S();
  s = s ?? Je.gatewayProtocol, n = n ?? Je.gatewayDomain;
  const o = s + "://" + n + e, c = yS(i, r);
  return a.post(o, {
    headers: {
      accept: "application/json"
    },
    data: c
  }).then(function(l) {
    t(l);
  }).catch(function(l) {
    t(void 0, l);
  }), c;
}
const Ae = {
  noAuthRequest(r, e, t) {
    return zr(!1, r, e, t);
  },
  noAuthRequestWithHost(r, e, t, i, s) {
    return zr(!1, t, i, s, r, e);
  },
  authRequest(r, e, t) {
    return zr(!0, r, e, t);
  },
  authRequestWithHost(r, e, t, i, s) {
    return zr(!0, t, i, s, r, e);
  },
  authRequestCallback(r, e, t) {
    return E1(!0, r, e, t);
  }
};
var Ts = /* @__PURE__ */ ((r) => (r[r.CACHE_ONLY = 0] = "CACHE_ONLY", r[r.CACHE_FIRST = 1] = "CACHE_FIRST", r))(Ts || {});
class xS {
  constructor(e, t) {
    y(this, "response");
    y(this, "time");
    this.response = e, this.time = t;
  }
}
const cs = class cs extends ve {
  constructor(t, i, s) {
    super();
    y(this, "cacheMode");
    y(this, "maxCacheTime");
    y(this, "refreshInterval");
    y(this, "cacheMap", /* @__PURE__ */ new Map());
    y(this, "requestFlagMap", /* @__PURE__ */ new Map());
    this.cacheMode = t, this.maxCacheTime = i ?? cs.DEFAULT_CACHE_TIME, this.refreshInterval = s ?? cs.DEFAULT_REFRESH_INTERVAL;
  }
  get TAG() {
    return `${cs.tag}:${this.newTag}`;
  }
  async request(t, i) {
    const s = await this.getCacheKey(t), n = this.cacheMap.get(s);
    let a = null;
    return n != null && (Date.now() - n.time < this.maxCacheTime ? a = n.response : this.cacheMap.delete(s)), a != null && this.cacheMode == 0 && !i ? (S.d(this.TAG, `${s} request return cache ${this.cacheMode} ${n == null ? void 0 : n.time} maxCacheTime=${this.maxCacheTime}`), a) : a == null || i ? this.requestFlagMap.get(s) ? (S.d(this.TAG, `${s} repeat request ${this.cacheMode} noCache=${i} maxCacheTime=${this.maxCacheTime}`), new Promise((o) => {
      this.once(s, (...c) => {
        const l = c[0];
        S.d(this.TAG, `${s} event emit noCache=${i}`), o(l);
      });
    })) : (this.requestFlagMap.set(s, !0), a = await this.doRequestAction("new", s, t), a) : (Date.now() - n.time > this.refreshInterval && this.requestFlagMap.get(s) && (this.requestFlagMap.set(s, !0), setTimeout(() => {
      this.doRequestAction("refresh", s, t);
    })), S.v(this.TAG, `${s} return cache ${this.cacheMode}`), a);
  }
  async doRequestAction(t, i, s) {
    const n = Date.now();
    try {
      const a = await this.doRequest(s);
      return S.d(this.TAG, `${i}  doRequest ${t} take ${Date.now() - n} ms`), a != null ? (this.updateCache(i, a), this.emit(i, a)) : this.emit(i), a;
    } finally {
      this.requestFlagMap.set(i, !1);
    }
  }
  updateCache(t, i) {
    i == null ? this.cacheMap.delete(t) : this.cacheMap.set(t, new xS(i, Date.now()));
  }
  getCache(t) {
    var i;
    return (i = this.cacheMap.get(t)) == null ? void 0 : i.response;
  }
};
y(cs, "tag", "RSC"), //默认缓存时长: 10分钟
y(cs, "DEFAULT_CACHE_TIME", 10 * 60 * 1e3), //默认刷新间隔
y(cs, "DEFAULT_REFRESH_INTERVAL", 0);
let zi = cs;
var Nr = /* @__PURE__ */ ((r) => (r.THING_INFO_GET = "/client/thing/info/get", r.THING_GET_PRODUCT_TSL = "/client/thing/tsl/getByProductKey", r.THING_PROPERTIES_GET_ALL = "/client/thing/properties/get/all", r.THING_PROPERTIES_SET = "/client/thing/properties/set", r.DEVICE_ENTITY_GET = "/client/device/entity/get", r.DEVICE_ENTITY_SET = "/client/device/entity/save", r.THING_STATUS_GET = "/client/thing/status/get", r))(Nr || {});
function $a(r, e, t = 0) {
  const i = e[r];
  if (i === void 0 || i == null) return;
  const n = i[t];
  return n.value && typeof n.value != "string" && (n.value = JSON.stringify(n.value)), n;
}
function vS(r, e) {
  var n;
  const t = He.CapsList, i = (n = $a(t, e)) == null ? void 0 : n.value;
  return i ? JSON.parse(i).includes(r) : !1;
}
function ES(r, e) {
  const t = $a(r, e);
  return t != null;
}
function SS(r, e) {
  var i;
  return !!((i = e.properties) == null ? void 0 : i.find((s) => s.identifier == r));
}
function TS(r, e) {
  var i;
  return !!((i = e.services) == null ? void 0 : i.find((s) => s.identifier == r));
}
const ql = {
  [Bt.CMD_THING_PROPERTY_CHANGE]: hs.DEVICE_THING_PROPERTIES_CHANGE,
  [Bt.CMD_THING_DELETE_NOTIFY]: hs.DEVICE_UNBIND,
  [Bt.CMD_THING_STATUS_NOTIFY]: hs.DEVICE_STATUS,
  [Bt.CMD_THING_INVOKE_SERVICE + "." + Um.devTransMsg]: hs.DEV_TRANS_MSG
}, ks = class ks {
  constructor(e, t, i) {
    y(this, "identifier");
    y(this, "requestId");
    y(this, "time", Date.now());
    this.identifier = e, this.requestId = t, i && (this.time = i);
  }
  static parse(e) {
    if (!e.includes(ks.SPLIT_CHAR)) return null;
    const [t, i, s] = e.split(ks.SPLIT_CHAR);
    try {
      return new ks(t, i, Number(s));
    } catch {
      S.e("WatchEventInfo", `WatchEventInfo parse error:${e}`);
    }
    return null;
  }
  toString() {
    return [this.identifier, this.requestId, this.time].join(ks.SPLIT_CHAR);
  }
};
y(ks, "SPLIT_CHAR", "^");
let Ka = ks;
class bS extends zi {
  constructor() {
    super(Ts.CACHE_FIRST, void 0, 5 * 60 * 1e3);
    y(this, "newTag", "TSLCache");
  }
  async getCacheKey(t) {
    return t.productKey;
  }
  async doRequest(t) {
    const i = t.productKey, s = t.deviceName, n = Nr.THING_GET_PRODUCT_TSL, a = {
      productKey: i,
      deviceName: s
    };
    return await Ae.authRequest(n, a);
  }
}
class AS extends zi {
  constructor() {
    super(Ts.CACHE_FIRST, void 0, 5 * 60 * 1e3);
    y(this, "newTag", "TSLCache");
  }
  async getCacheKey(t) {
    return t.iotId;
  }
  async doRequest(t) {
    const i = t.iotId, s = Nr.THING_PROPERTIES_GET_ALL;
    return await Ae.authRequest(s, { iotId: i });
  }
}
const CS = new bS(), RS = new AS();
async function tc(r, e) {
  var i;
  return (i = (await RS.request({ iotId: r }, e)).data) == null ? void 0 : i.propertyMap;
}
async function fd(r) {
  const e = await tc(r, !1), t = {}, i = $a(He.LensCount, e);
  return t[He.LensCount] = Number((i == null ? void 0 : i.value) || 1), [
    He.CodecList,
    He.VideoCodec,
    He.AudioCodec,
    He.SubVideoCodec,
    He.SubAudioCodec,
    He.TalkAudioCodec,
    He.powerstate,
    He.DeviceWorkMode,
    He.DeviceSdkAbility
  ].forEach((n) => {
    const a = $a(n, e);
    t[n] = a == null ? void 0 : a.value;
  }), t;
}
const IS = 1e4;
class LS {
  constructor(e) {
    y(this, "TAG", "CloudThingModelPanel");
    y(this, "deviceInfo");
    y(this, "setPropertyEventEmitter", new ve());
    y(this, "setPropertyTimeout", IS);
    y(this, "panelEventCallbacks", []);
    y(this, "thingPropertiesCache");
    y(this, "thingTSLCache");
    y(this, "onNotifyMessage", (e) => {
      const { productKey: t, deviceName: i, iotId: s } = this.deviceInfo, n = ql[e.method];
      if (!n) return;
      var a = e.productKey === t && e.deviceName === i;
      const o = e.params;
      a || (a = (o == null ? void 0 : o.iotId) === s), a && (S.d(this.TAG, `subscribe type=${n}`, o), n === hs.DEVICE_THING_PROPERTIES_CHANGE && Object.keys(o).forEach((c) => {
        this.matchSetPropertyNotify(e.id, c);
      }), this.panelEventCallbacks.forEach((c) => {
        c(s, n, o);
      }), n == hs.DEVICE_UNBIND && this.destroy());
    });
    this.deviceInfo = e;
  }
  destroy() {
    this.panelEventCallbacks = [], this.setPropertyEventEmitter.removeAllListeners(), this.unregisterTopic();
  }
  setPropertiesTimeout(e) {
    this.setPropertyTimeout = Math.max(e, 5e3);
  }
  subscribe(e) {
    this.registerTopic(), this.panelEventCallbacks.includes(e) || this.panelEventCallbacks.push(e);
  }
  unsubscribe(e) {
    const t = this.panelEventCallbacks.findIndex((i) => i === e);
    t > -1 && this.panelEventCallbacks.splice(t, 1);
  }
  async getThingProperties() {
    const { iotId: e } = this.deviceInfo;
    return await tc(e, !0);
  }
  async setProperties(e, t) {
    this.registerTopic();
    let i;
    const { iotId: s } = this.deviceInfo;
    return new Promise((n, a) => {
      let o;
      const c = () => {
        clearTimeout(o), n(!0);
      }, l = { iotId: s, items: e, lensId: t }, d = Ae.authRequestCallback(
        Nr.THING_PROPERTIES_SET,
        (u, f) => {
          if (f) {
            i && this.setPropertyEventEmitter.off(i, c), S.e(this.TAG, "setProperties", f), a(f);
            return;
          }
        },
        l
      );
      i = new Ka(Object.keys(e)[0], d.id).toString(), S.i(this.TAG, `setProperties watch notify: ${i}`), this.setPropertyEventEmitter.once(i, c), o = setTimeout(() => {
        i && this.setPropertyEventEmitter.off(i, c), S.w(this.TAG, `setProperties watch timeout: ${i}`), a(new ur("set thing properties timeout"));
      }, this.setPropertyTimeout);
    });
  }
  async getThingTsl() {
    const { productKey: e, deviceName: t } = this.deviceInfo, i = {
      productKey: e,
      deviceName: t
    };
    return (await CS.request(i, !1)).data;
  }
  async invokeService(e, t, i = !1, s, n) {
    const { productKey: a, deviceName: o } = this.deviceInfo, c = {
      productKey: a,
      deviceName: o,
      lensId: s,
      identifier: e,
      params: t,
      ack: i ? Ke.NEED_ACK : Ke.NO_ACK,
      timeout: n
    }, l = await Ii().invokeThingService(c);
    return l && {
      code: l.code,
      data: l.data
    };
  }
  async getCachePropertiesAndTSL() {
    const { iotId: e } = this.deviceInfo, [t, i] = await Promise.all([
      this.thingPropertiesCache ? Promise.resolve(this.thingPropertiesCache) : tc(e, !1),
      this.thingTSLCache ? Promise.resolve(this.thingTSLCache) : this.getThingTsl()
    ]);
    return this.thingPropertiesCache = t, this.thingTSLCache = i, { propertiesMap: t, tsl: i };
  }
  async supportProperty(e) {
    try {
      const { propertiesMap: t, tsl: i } = await this.getCachePropertiesAndTSL();
      return ES(e, t) && SS(e, i);
    } catch {
      return !1;
    }
  }
  async supportService(e) {
    const { propertiesMap: t, tsl: i } = await this.getCachePropertiesAndTSL();
    return await this.supportProperty(He.CapsList) ? vS(e, t) : TS(e, i);
  }
  registerTopic() {
    const { productKey: e, deviceName: t, iotId: i } = this.deviceInfo, s = Ii();
    s.registerTopic(e, t, 0, { iotId: i }), Object.keys(ql).forEach((n) => {
      s.listeners(n).includes(this.onNotifyMessage) || s.on(n, this.onNotifyMessage);
    });
  }
  unregisterTopic() {
    const { productKey: e, deviceName: t, iotId: i } = this.deviceInfo, s = Ii();
    s.unregisterTopic(e, t, 0, { iotId: i }), Object.keys(ql).forEach((n) => {
      s.off(n, this.onNotifyMessage);
    });
  }
  /**
   * 匹配设置属性设置请求与通知消息
   *
   */
  matchSetPropertyNotify(e, t) {
    var n;
    const i = this.setPropertyEventEmitter.eventNames().filter((a) => typeof a == "string");
    var s = i.find((a) => a.includes(e));
    if (!s) {
      const a = i.map((o) => Ka.parse(o)).filter((o) => o != null);
      a.sort((o, c) => c.time - o.time), s = (n = a.find((o) => {
        o.identifier == t;
      })) == null ? void 0 : n.toString();
    }
    if (s) {
      S.i(this.TAG, `matched property change: ${s}`), this.setPropertyEventEmitter.emit(s);
      return;
    }
  }
}
var ic = /* @__PURE__ */ ((r) => (r.PNS_SCHEDULE_GET = "/client/pns/schedule/get", r.PNS_SCHEDULE_SET = "/client/pns/schedule/set", r))(ic || {});
class DS extends zi {
  constructor(t) {
    super(Ts.CACHE_FIRST, 5 * 60 * 1e3, 0);
    y(this, "mGatewayAPIUtil", Ae);
    y(this, "mDeviceEntityAPI", Nr);
    y(this, "newTag");
    this.newTag = t;
  }
  /**
   * 获取推送配置
   *
   * @param iotId
   * @param ioTCallback
   */
  getPushSchedule(t) {
    const i = { iotId: t };
    return this.mGatewayAPIUtil.authRequest(ic.PNS_SCHEDULE_GET, i);
  }
  /**
   * 设置推送
   *
   * @param iotId
   * @param setting
   * @param ioTCallback
   */
  setPushSchedule(t, i) {
    const s = {
      iotId: t,
      schedule: i
    };
    this.mGatewayAPIUtil.authRequest(ic.PNS_SCHEDULE_SET, s);
  }
  /**
   * 设置设备配置项（单个）
   *
   * @param iotId 设备ID
   * @param entityEnum 设置项
   * @param value 设置内容
   * @param ioTCallback 回调
   */
  setDeviceEntity(t, i, s) {
    switch (i) {
      case ms.MSG_PUSH_SETTING:
        return this.setPushSchedule(t, s);
      default: {
        const n = {
          [i]: s
        };
        return this.setDeviceEntities(t, n);
      }
    }
  }
  /**
   * 设置设备配置(批量)
   *
   * @param iotId
   * @param attributeList
   * @param entityType [DeviceEntityDimensionEnum]
   */
  setDeviceEntities(t, i, s = en.DEVICE) {
    return this.mGatewayAPIUtil.authRequest(this.mDeviceEntityAPI.DEVICE_ENTITY_SET, {
      iotId: t,
      attributeList: Object.entries(i).map((n, a) => ({
        id: n,
        value: a
      })),
      entityType: s
      //默认0，0：设备类型，2：用户设备类型
    });
  }
  /**
   * 获指定配置项
   *
   * @param iotId 设备ID
   * @param entityEnum 配置项
   * @param listener 回调
   */
  async getDeviceEntity(t, i) {
    var s, n;
    switch (i) {
      case ms.MSG_PUSH_SETTING: {
        const a = await this.getPushSchedule(t);
        return (s = a == null ? void 0 : a.data) == null ? void 0 : s.schedule;
      }
      default: {
        const a = await this.getDeviceEntities(t, [i]);
        return (n = a == null ? void 0 : a[i]) == null ? void 0 : n.value;
      }
    }
  }
  /**
   * 获取设备配置(按维度)
   *
   * @param iotId
   * @param attributeIdList
   * @param entityType [DeviceEntityDimensionEnum]
   * @param listener
   */
  async getDeviceEntities(t, i = [], s = en.DEVICE) {
    return this.getAllDeviceEntities(t, s).then((n) => n && i.reduce((a, o) => {
      const c = o.toString();
      return a[c] = n[c], a;
    }, {}));
  }
  async getAllDeviceEntities(t, i = en.DEVICE) {
    const s = Object.values(ms).filter(Number.isInteger);
    let n;
    const a = {
      iotId: t,
      attributeIdList: s,
      entityType: i,
      //实体类型， 默认0，0：设备维度类型，2：用户设备类型
      lastUpdateTime: n
    }, o = await this.getCacheKey(a), c = this.getCache(o);
    n = Number((c == null ? void 0 : c.maxUpdateTimeValue) || 0), n > 0 && (a.lastUpdateTime = n);
    const l = await this.request(a, !1);
    return l == null ? void 0 : l.attributeMap;
  }
  async getCacheKey(t) {
    return t.iotId;
  }
  async doRequest(t) {
    const i = await this.getCacheKey(t), s = this.getCache(i);
    (!(s != null && s.attributeMap) || Object.keys(s == null ? void 0 : s.attributeMap).length === 0) && (t.lastUpdateTime = void 0);
    const n = await this.mGatewayAPIUtil.authRequest(this.mDeviceEntityAPI.DEVICE_ENTITY_GET, t), a = n == null ? void 0 : n.data;
    if (a) {
      const o = Object.assign({}, s == null ? void 0 : s.attributeMap, a == null ? void 0 : a.attributeMap);
      a.attributeMap = o;
    }
    return Object.assign({}, s, a);
  }
}
const Wn = new DS("DeviceEntityMgr"), sc = {
  /**
   * 设置设备配置项（单个）
   *
   * @param iotId 设备ID
   * @param entityEnum 设置项
   * @param value 设置内容
   */
  setDeviceEntity(r, e, t) {
    return Wn.setDeviceEntity(r, e, t);
  },
  setDeviceEntities(r, e) {
    return Wn.setDeviceEntities(r, e);
  },
  /**
   * 获指定ID配置
   *
   * @param iotId 设备ID
   * @param entityEnum 配置ID
   * @param listener
   */
  getDeviceEntity(r, e) {
    return Wn.getDeviceEntity(r, e);
  },
  /**
   * 获取设备配置(按维度)
   *
   * @param iotId
   * @param entityType [DeviceEntityDimensionEnum]
   * @param attributeIdList
   * @param listener
   */
  getDeviceEntities(r, e, t) {
    return Wn.getDeviceEntities(r, e, t);
  }
};
var S1 = /* @__PURE__ */ ((r) => (r.DEVICE_CURRENT_SERVICE = "/client/device/cloudstorage/current/get", r.DEVICE_SERVICE_HISTORY = "/client/device/cloudstorage/history", r))(S1 || {});
async function PS(r) {
  return (await Ae.authRequest(S1.DEVICE_CURRENT_SERVICE, { iotId: r })).data;
}
class kS extends zi {
  constructor() {
    super(Ts.CACHE_FIRST, void 0, 60 * 1e3);
    y(this, "newTag", "DeviceCurrentServiceCacheMgr");
  }
  async getCacheKey(t) {
    return t.iotId;
  }
  async doRequest(t) {
    return PS(t.iotId);
  }
}
const T1 = new kS(), bo = "DeviceMgr";
async function pd(r) {
  const e = Nr.THING_STATUS_GET;
  return (await Ae.authRequest(e, { iotId: r })).data.status ?? yo.UNKNOWN;
}
async function wS(r) {
  S.i(bo, "getDeviceList params=", r);
  const e = vt.LIST_BINDING_BY_ACCOUNT, i = (await Ae.authRequest(e, r)).data, s = i.data.map((n) => new xo(n));
  return await Promise.allSettled(s.map(md)), i.data = s, i;
}
async function MS(r) {
  if (!r.length)
    throw new Lt("devicelist is empty");
  const e = r.map((i) => new xo(i)), t = e.map((i) => Promise.allSettled([md(i), pd(i.iotId).then((s) => i.status = s)]));
  return await Promise.allSettled(t), e;
}
async function BS(r) {
  S.i(bo, "getGatewaySubList params=", r);
  const e = vt.SUB_DEVICE_LIST, t = {
    iotId: r.deviceInfo.iotId,
    pageNo: r.pageNo,
    pageSize: r.pageSize,
    groupId: r.groupId
  }, s = (await Ae.authRequest(e, t)).data;
  Om(r.deviceInfo, s.data);
  const n = s.data.map((a) => {
    const o = new xo(a);
    return o.parentNodeType = rd.GATEWAY, o;
  });
  return await Promise.allSettled(n.map(md)), s.data = n, s;
}
function FS(r, e) {
  Om(r, e);
}
async function md(r) {
  const e = r.iotId;
  sc.getDeviceEntity(e, ms.LIVE_PLAY_STRATEGY), T1.request({ iotId: e }, !1);
  const t = await fd(e);
  r.thingProperties = t;
}
async function rc(r) {
  const e = {
    iotId: r
  }, t = vt.DEVICE_WAKE_UP;
  await Ae.authRequest(t, e);
}
async function OS(r) {
  S.d(bo, `unbindAccountAndDev iotId=${r}`);
  const e = vt.UNBIND_ACCOUNT_AND_DEV;
  await Ae.authRequest(e, { iotId: r });
}
async function NS(r, e) {
  S.d(bo, `unbindAccountAndDev iotId=${r}`);
  const t = vt.SET_DEVICE_NICK_NAME;
  await Ae.authRequest(t, { iotId: r, nickName: e });
}
const f6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  deviceWakeUp: rc,
  getDeviceDetail: MS,
  getDeviceList: wS,
  getDeviceStatus: pd,
  getGatewaySubList: BS,
  setDeviceNickName: NS,
  setGatewayDeviceRelevance: FS,
  unbindAccountAndDev: OS
}, Symbol.toStringTag, { value: "Module" }));
class p6 {
  /**
   *
   * @param iotId - 设备唯一ID
   * @param wakeupTimeout - 超时时长 单位:毫秒  默认30_000
   * @param checkStatusInterval - 轮询设备状态频率 单位:毫秒  默认1000
   */
  constructor(e, t = 3e4, i = 1e3) {
    y(this, "TAG", "DeviceWakeUpMgr");
    y(this, "id", _o());
    y(this, "iotId");
    y(this, "wakeupTimeout");
    y(this, "checkStatusInterval");
    y(this, "timeoutTimer");
    y(this, "checkStatusTimer");
    y(this, "retryWakeupInterval", 500);
    this.iotId = e, this.wakeupTimeout = t, this.checkStatusInterval = Math.max(i, 1e3);
  }
  /**
   * 唤醒设备，等待设备上线
   */
  async wakeup() {
    S.i(this.TAG, `wakeup start timeout=${this.wakeupTimeout} interval=${this.checkStatusInterval} ${this.id}`), this.doStop(), await Promise.allSettled([rc(this.iotId), this.startCheckStatus()]);
  }
  /**
   * 结束唤醒流程
   */
  stop() {
    S.i(this.TAG, `wakeup stop ${this.id}`), this.doStop();
  }
  doStop() {
    this.stopCheckStatus(), clearTimeout(this.timeoutTimer), this.retryWakeupInterval = 500;
  }
  stopCheckStatus() {
    S.i(this.TAG, `wake refresh status stop. timer=${this.checkStatusTimer} ${this.id}`), clearTimeout(this.checkStatusTimer);
  }
  startCheckStatus() {
    return this.stopCheckStatus(), S.i(this.TAG, `wake refresh status start. interval=${this.checkStatusInterval} ${this.id}`), new Promise((e, t) => {
      var i = Date.now();
      this.checkStatusTimer = setInterval(async () => {
        const s = await pd(this.iotId);
        if (s == yo.ONLINE)
          this.doStop(), e(s);
        else {
          const n = Date.now();
          n - i > this.retryWakeupInterval && (this.retryWakeupInterval = Math.min(this.retryWakeupInterval * 2, 4e3), i = n, rc(this.iotId));
        }
      }, this.checkStatusInterval), this.timeoutTimer = setTimeout(() => {
        this.doStop();
        const s = new pt(ki.WakeUpTimeout, "device wakeup timeout");
        t(s);
      }, this.wakeupTimeout);
    });
  }
}
class GS {
  constructor() {
    /**
     * 数据中心服务协议
     */
    y(this, "dataCenterScheme");
    /**
     * 数据中心服务域名
     */
    y(this, "dataCenterDomain");
    /**
     * 数据中心服务域名类型
     */
    y(this, "dataCenterDomainType");
    /**
     * 自动加上AK
     */
    y(this, "domainAutoWidthAK");
    /**
     * 信令协议
     */
    y(this, "signalingScheme");
    /**
     * 信令域名
     */
    y(this, "signalingDomain");
    /**
     * STUN服务地址
     */
    y(this, "stunAddress");
    /**
     * 控制台创建的应用key
     */
    y(this, "appKey", "");
    /**
     * 控制台创建的应用Secret
     */
    y(this, "appSecret", "");
  }
}
class US {
  constructor() {
    /**
     * 接入区域（国内或海外）
     */
    y(this, "regionType", vs.REGION_CHINA_ONLY);
    /**
     * 环境
     */
    y(this, "productEnv", hi.PROD);
    /**
     * 是否开启日志调试
     */
    y(this, "debug", !1);
    /**
     * 通用版App配置项
     */
    y(this, "appKeyConfig");
    /**
     * 专属版App配置项
     */
    y(this, "specialAppKeyConfig");
  }
}
const m6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AppKeyConfig: GS,
  InitConfig: US
}, Symbol.toStringTag, { value: "Module" }));
var gd = /* @__PURE__ */ ((r) => (r.DATA_CENTER_GET = "/client/datacenter/get", r.SERVICE_GET_BY_REGION_ID = "/client/datacenter/getByRegionId", r))(gd || {});
class VS {
  constructor(e, t, i, s) {
    y(this, "name");
    y(this, "domain");
    y(this, "protocol");
    y(this, "desc");
    this.name = e, this.domain = t, this.protocol = i, this.desc = s;
  }
}
const b1 = new Cm("86", "ZhongGuoDaLu", "CHN", "中国大陆", "CN"), A1 = [gs.GATEWAY, gs.STUN], C1 = 3, fs = "SDKInit";
let ya = !1;
async function WS(r) {
  const { appKeyConfig: e, specialAppKeyConfig: t, debug: i, productEnv: s, regionType: n } = r;
  if (S.i(fs, `init sdk start. isInitSdk=${ya}`), ya) {
    const o = "SDK has been initialized multiple times, please check the code";
    throw S.e(fs, o), o;
  }
  if (ya = !0, HS(i), !e && !t) {
    const o = "need app key and secret";
    throw S.e(fs, o), o;
  }
  if (re.platformEnv = s, e) {
    re.appKey = e.appKey, re.appSecret = e.appSecret, e.dataCenterScheme && (re.dataCenterSchema = e.dataCenterScheme);
    const o = e.dataCenterDomain;
    o && (re.dataCenterDomain = o, re.domainAutoWithAK = typeof e.domainAutoWidthAK == "boolean" ? e.domainAutoWidthAK : !1), e.dataCenterDomainType && (re.dataCenterDomainType = e.dataCenterDomainType), e.signalingScheme && (re.signalingSchema = e.signalingScheme), e.signalingDomain && (re.signalingDomain = e.signalingDomain), re.dataCenterDomainType === mo.GATEWAY && e.stunAddress && (Je.stunAddress = e.stunAddress);
  }
  if (t) {
    re.specialAppKey = t.appKey, re.specialAppSecret = t.appSecret, t.dataCenterScheme && (re.specialDataCenterSchema = t.dataCenterScheme);
    const o = t.dataCenterDomain;
    o && (re.specialDataCenterDomain = o), t.signalingScheme && (re.specialSignalingSchema = t.signalingScheme), t.signalingDomain && (re.specialDataCenterDomain = t.signalingDomain);
  }
  if (re.regionType = n, a2(ps.COMMON)) {
    if (S.i(fs, `common sdk setCountry regionType=${n}`), n == vs.REGION_CHINA_ONLY)
      return nc(b1);
    if (re.country)
      return nc(re.country);
  }
}
function HS(r) {
  S.ENABLE_DEBUG = r, S.ENABLE_VERBOSE = r;
}
async function ZS() {
  ya = !1, wi.clear(), re.clear();
}
function $S() {
  return Je.regionId;
}
function KS() {
  return re.regionType;
}
function XS() {
  return re.country;
}
async function YS(r) {
  re.locale = r;
}
function zS() {
  return re.locale;
}
async function nc(r, e) {
  var t;
  if (S.i(fs, "setCountry", r), re.regionType == vs.REGION_CHINA_ONLY && b1.isoCode != r.isoCode.toUpperCase()) {
    S.w(fs, "not need setCountry when regionType is REGION_CHINA_ONLY");
    return;
  }
  ((t = re.country) == null ? void 0 : t.isoCode) != r.isoCode && (Je.regionId = -1), e != null && e > -1 && (Je.regionId != e && (re.country = r), Je.regionId = e), await jS(r);
}
async function jS(r) {
  const e = QS();
  S.i(fs, "setUserCountry country & dataCenterDomain", r, e);
  try {
    await eT(e, r);
  } catch (t) {
    S.e(fs, "get dns failed", t);
  } finally {
    re.country = r;
  }
}
function QS() {
  const r = re.platformEnv, e = o2[r], t = re.regionType == vs.REGION_CHINA_ONLY;
  return re.dataCenterSchema || (re.dataCenterSchema = e.protocol === xt.HTTPS ? xt.HTTPS : xt.HTTP), re.dataCenterDomain || (re.dataCenterDomain = t ? e.domainChina : e.domainAbroad), new VS("dataCenter", re.dataCenterDomain, re.dataCenterSchema);
}
function R1(r) {
  let e = r.domain;
  return re.platformEnv == hi.PROD && re.domainAutoWithAK && (e = re.appKey + "." + e), e;
}
async function JS(r, e) {
  const t = R1(r), i = r.protocol, s = {
    services: A1,
    clientUniqueKey: Rn(),
    domainAbbreviation: e.domainAbbreviation
  };
  return Ae.noAuthRequestWithHost(i, t, gd.DATA_CENTER_GET, s, C1);
}
async function qS(r, e) {
  const t = R1(r), i = r.protocol, s = {
    services: A1,
    regionId: e
  };
  return Ae.noAuthRequestWithHost(i, t, gd.SERVICE_GET_BY_REGION_ID, s, C1);
}
async function eT(r, e) {
  if (re.dataCenterDomainType == mo.GATEWAY) {
    Je.gatewayProtocol = r.protocol, Je.gatewayDomain = r.domain;
    return;
  }
  const t = Je.regionId, i = await (t < 0 ? JS(r, e) : qS(r, t)), s = i.data;
  if (s != null) {
    const { regionId: n, addresses: a } = s;
    n && (Je.regionId = n), a.forEach((o) => {
      switch (o.name) {
        case gs.GATEWAY: {
          Je.gatewayProtocol = o.protocol, Je.gatewayDomain = o.domain;
          break;
        }
        case gs.STUN: {
          Je.stunAddress = o.protocol + ":" + o.domain;
          break;
        }
      }
    });
  }
  return i;
}
const g6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  getCountry: XS,
  getLocale: zS,
  getRegionId: $S,
  getRegionType: KS,
  init: WS,
  setCountry: nc,
  setLocale: YS,
  uninit: ZS
}, Symbol.toStringTag, { value: "Module" }));
var ji = /* @__PURE__ */ ((r) => (r.USERNAME = "1", r.MOBILE = "2", r.EMAIL = "3", r.ONE_KEY = "4", r.THIRD_LOGIN = "6", r))(ji || {}), Os = /* @__PURE__ */ ((r) => (r.PASSWORD = "1", r.EMAIL_CODE = "2", r.MOBILE_CODE = "3", r.AUTH2_CODE = "4", r))(Os || {});
const _6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AccountTypeEnum: ji,
  PasswordTypeEnum: Os
}, Symbol.toStringTag, { value: "Module" }));
var I1 = { exports: {} }, L1 = { exports: {} };
(function() {
  var r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", e = {
    // Bit-wise rotation left
    rotl: function(t, i) {
      return t << i | t >>> 32 - i;
    },
    // Bit-wise rotation right
    rotr: function(t, i) {
      return t << 32 - i | t >>> i;
    },
    // Swap big-endian to little-endian and vice versa
    endian: function(t) {
      if (t.constructor == Number)
        return e.rotl(t, 8) & 16711935 | e.rotl(t, 24) & 4278255360;
      for (var i = 0; i < t.length; i++)
        t[i] = e.endian(t[i]);
      return t;
    },
    // Generate an array of any length of random bytes
    randomBytes: function(t) {
      for (var i = []; t > 0; t--)
        i.push(Math.floor(Math.random() * 256));
      return i;
    },
    // Convert a byte array to big-endian 32-bit words
    bytesToWords: function(t) {
      for (var i = [], s = 0, n = 0; s < t.length; s++, n += 8)
        i[n >>> 5] |= t[s] << 24 - n % 32;
      return i;
    },
    // Convert big-endian 32-bit words to a byte array
    wordsToBytes: function(t) {
      for (var i = [], s = 0; s < t.length * 32; s += 8)
        i.push(t[s >>> 5] >>> 24 - s % 32 & 255);
      return i;
    },
    // Convert a byte array to a hex string
    bytesToHex: function(t) {
      for (var i = [], s = 0; s < t.length; s++)
        i.push((t[s] >>> 4).toString(16)), i.push((t[s] & 15).toString(16));
      return i.join("");
    },
    // Convert a hex string to a byte array
    hexToBytes: function(t) {
      for (var i = [], s = 0; s < t.length; s += 2)
        i.push(parseInt(t.substr(s, 2), 16));
      return i;
    },
    // Convert a byte array to a base-64 string
    bytesToBase64: function(t) {
      for (var i = [], s = 0; s < t.length; s += 3)
        for (var n = t[s] << 16 | t[s + 1] << 8 | t[s + 2], a = 0; a < 4; a++)
          s * 8 + a * 6 <= t.length * 8 ? i.push(r.charAt(n >>> 6 * (3 - a) & 63)) : i.push("=");
      return i.join("");
    },
    // Convert a base-64 string to a byte array
    base64ToBytes: function(t) {
      t = t.replace(/[^A-Z0-9+\/]/ig, "");
      for (var i = [], s = 0, n = 0; s < t.length; n = ++s % 4)
        n != 0 && i.push((r.indexOf(t.charAt(s - 1)) & Math.pow(2, -2 * n + 8) - 1) << n * 2 | r.indexOf(t.charAt(s)) >>> 6 - n * 2);
      return i;
    }
  };
  L1.exports = e;
})();
var tT = L1.exports, ac = {
  // UTF-8 encoding
  utf8: {
    // Convert a string to a byte array
    stringToBytes: function(r) {
      return ac.bin.stringToBytes(unescape(encodeURIComponent(r)));
    },
    // Convert a byte array to a string
    bytesToString: function(r) {
      return decodeURIComponent(escape(ac.bin.bytesToString(r)));
    }
  },
  // Binary encoding
  bin: {
    // Convert a string to a byte array
    stringToBytes: function(r) {
      for (var e = [], t = 0; t < r.length; t++)
        e.push(r.charCodeAt(t) & 255);
      return e;
    },
    // Convert a byte array to a string
    bytesToString: function(r) {
      for (var e = [], t = 0; t < r.length; t++)
        e.push(String.fromCharCode(r[t]));
      return e.join("");
    }
  }
}, Uu = ac;
/*!
 * Determine if an object is a Buffer
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
var iT = function(r) {
  return r != null && (D1(r) || sT(r) || !!r._isBuffer);
};
function D1(r) {
  return !!r.constructor && typeof r.constructor.isBuffer == "function" && r.constructor.isBuffer(r);
}
function sT(r) {
  return typeof r.readFloatLE == "function" && typeof r.slice == "function" && D1(r.slice(0, 0));
}
(function() {
  var r = tT, e = Uu.utf8, t = iT, i = Uu.bin, s = function(n, a) {
    n.constructor == String ? a && a.encoding === "binary" ? n = i.stringToBytes(n) : n = e.stringToBytes(n) : t(n) ? n = Array.prototype.slice.call(n, 0) : !Array.isArray(n) && n.constructor !== Uint8Array && (n = n.toString());
    for (var o = r.bytesToWords(n), c = n.length * 8, l = 1732584193, d = -271733879, h = -1732584194, u = 271733878, f = 0; f < o.length; f++)
      o[f] = (o[f] << 8 | o[f] >>> 24) & 16711935 | (o[f] << 24 | o[f] >>> 8) & 4278255360;
    o[c >>> 5] |= 128 << c % 32, o[(c + 64 >>> 9 << 4) + 14] = c;
    for (var p = s._ff, m = s._gg, g = s._hh, x = s._ii, f = 0; f < o.length; f += 16) {
      var _ = l, v = d, E = h, b = u;
      l = p(l, d, h, u, o[f + 0], 7, -680876936), u = p(u, l, d, h, o[f + 1], 12, -389564586), h = p(h, u, l, d, o[f + 2], 17, 606105819), d = p(d, h, u, l, o[f + 3], 22, -1044525330), l = p(l, d, h, u, o[f + 4], 7, -176418897), u = p(u, l, d, h, o[f + 5], 12, 1200080426), h = p(h, u, l, d, o[f + 6], 17, -1473231341), d = p(d, h, u, l, o[f + 7], 22, -45705983), l = p(l, d, h, u, o[f + 8], 7, 1770035416), u = p(u, l, d, h, o[f + 9], 12, -1958414417), h = p(h, u, l, d, o[f + 10], 17, -42063), d = p(d, h, u, l, o[f + 11], 22, -1990404162), l = p(l, d, h, u, o[f + 12], 7, 1804603682), u = p(u, l, d, h, o[f + 13], 12, -40341101), h = p(h, u, l, d, o[f + 14], 17, -1502002290), d = p(d, h, u, l, o[f + 15], 22, 1236535329), l = m(l, d, h, u, o[f + 1], 5, -165796510), u = m(u, l, d, h, o[f + 6], 9, -1069501632), h = m(h, u, l, d, o[f + 11], 14, 643717713), d = m(d, h, u, l, o[f + 0], 20, -373897302), l = m(l, d, h, u, o[f + 5], 5, -701558691), u = m(u, l, d, h, o[f + 10], 9, 38016083), h = m(h, u, l, d, o[f + 15], 14, -660478335), d = m(d, h, u, l, o[f + 4], 20, -405537848), l = m(l, d, h, u, o[f + 9], 5, 568446438), u = m(u, l, d, h, o[f + 14], 9, -1019803690), h = m(h, u, l, d, o[f + 3], 14, -187363961), d = m(d, h, u, l, o[f + 8], 20, 1163531501), l = m(l, d, h, u, o[f + 13], 5, -1444681467), u = m(u, l, d, h, o[f + 2], 9, -51403784), h = m(h, u, l, d, o[f + 7], 14, 1735328473), d = m(d, h, u, l, o[f + 12], 20, -1926607734), l = g(l, d, h, u, o[f + 5], 4, -378558), u = g(u, l, d, h, o[f + 8], 11, -2022574463), h = g(h, u, l, d, o[f + 11], 16, 1839030562), d = g(d, h, u, l, o[f + 14], 23, -35309556), l = g(l, d, h, u, o[f + 1], 4, -1530992060), u = g(u, l, d, h, o[f + 4], 11, 1272893353), h = g(h, u, l, d, o[f + 7], 16, -155497632), d = g(d, h, u, l, o[f + 10], 23, -1094730640), l = g(l, d, h, u, o[f + 13], 4, 681279174), u = g(u, l, d, h, o[f + 0], 11, -358537222), h = g(h, u, l, d, o[f + 3], 16, -722521979), d = g(d, h, u, l, o[f + 6], 23, 76029189), l = g(l, d, h, u, o[f + 9], 4, -640364487), u = g(u, l, d, h, o[f + 12], 11, -421815835), h = g(h, u, l, d, o[f + 15], 16, 530742520), d = g(d, h, u, l, o[f + 2], 23, -995338651), l = x(l, d, h, u, o[f + 0], 6, -198630844), u = x(u, l, d, h, o[f + 7], 10, 1126891415), h = x(h, u, l, d, o[f + 14], 15, -1416354905), d = x(d, h, u, l, o[f + 5], 21, -57434055), l = x(l, d, h, u, o[f + 12], 6, 1700485571), u = x(u, l, d, h, o[f + 3], 10, -1894986606), h = x(h, u, l, d, o[f + 10], 15, -1051523), d = x(d, h, u, l, o[f + 1], 21, -2054922799), l = x(l, d, h, u, o[f + 8], 6, 1873313359), u = x(u, l, d, h, o[f + 15], 10, -30611744), h = x(h, u, l, d, o[f + 6], 15, -1560198380), d = x(d, h, u, l, o[f + 13], 21, 1309151649), l = x(l, d, h, u, o[f + 4], 6, -145523070), u = x(u, l, d, h, o[f + 11], 10, -1120210379), h = x(h, u, l, d, o[f + 2], 15, 718787259), d = x(d, h, u, l, o[f + 9], 21, -343485551), l = l + _ >>> 0, d = d + v >>> 0, h = h + E >>> 0, u = u + b >>> 0;
    }
    return r.endian([l, d, h, u]);
  };
  s._ff = function(n, a, o, c, l, d, h) {
    var u = n + (a & o | ~a & c) + (l >>> 0) + h;
    return (u << d | u >>> 32 - d) + a;
  }, s._gg = function(n, a, o, c, l, d, h) {
    var u = n + (a & c | o & ~c) + (l >>> 0) + h;
    return (u << d | u >>> 32 - d) + a;
  }, s._hh = function(n, a, o, c, l, d, h) {
    var u = n + (a ^ o ^ c) + (l >>> 0) + h;
    return (u << d | u >>> 32 - d) + a;
  }, s._ii = function(n, a, o, c, l, d, h) {
    var u = n + (o ^ (a | ~c)) + (l >>> 0) + h;
    return (u << d | u >>> 32 - d) + a;
  }, s._blocksize = 16, s._digestsize = 16, I1.exports = function(n, a) {
    if (n == null)
      throw new Error("Illegal argument " + n);
    var o = r.wordsToBytes(s(n, a));
    return a && a.asBytes ? o : a && a.asString ? i.bytesToString(o) : r.bytesToHex(o);
  };
})();
var rT = I1.exports;
const nT = /* @__PURE__ */ Fr(rT);
var mn = /* @__PURE__ */ ((r) => (r.USER_LOGIN = "/client/account/login", r.ACCOUNT_LOGOUT = "/client/account/logout", r.ACCOUNT_THIRD_LOGIN = "/client/account/third/login", r.USER_ENTITY_GET = "/client/user/entity/get", r))(mn || {});
function P1(r) {
  return r ? /^([a-z0-9A-Z_]+[-|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$/.test(r) : !1;
}
var _d = /* @__PURE__ */ ((r) => (r[r.LIVE_PLAY_DURATION_LIMIT = 2e3] = "LIVE_PLAY_DURATION_LIMIT", r))(_d || {});
class aT extends zi {
  constructor(t) {
    super(Ts.CACHE_FIRST, 5 * 60 * 1e3, 0);
    y(this, "mGatewayAPIUtil", Ae);
    y(this, "newTag", "UserEntityMgrBase");
    this.newTag = t;
  }
  /**
   * 获指定ID配置
   *
   * @param entityId
   * @param listener
   */
  async getUserEntity(t) {
    var n;
    const i = await this.getUserEntities([t]);
    return (n = i == null ? void 0 : i[t.toString()]) == null ? void 0 : n.value;
  }
  /**
   * 获取用户所有配置
   *
   * @param listener
   */
  async getUserEntities(t) {
    return this.getAllUserEntities().then((i) => i && t.reduce((s, n) => {
      const a = n.toString();
      return s[a] = i[a], s;
    }, {}));
  }
  async getAllUserEntities() {
    const t = Object.values(_d).filter(Number.isInteger);
    let i;
    const s = {
      attributeIdList: t,
      lastUpdateTime: i
    }, n = await this.getCacheKey(s), a = this.getCache(n);
    i = Number((a == null ? void 0 : a.maxUpdateTimeValue) || 0), i > 0 && (s.lastUpdateTime = i);
    const o = await this.request(s, !1);
    return o == null ? void 0 : o.attributeMap;
  }
  async getCacheKey(t) {
    return wi.getUserId().toString();
  }
  async doRequest(t) {
    const i = await this.getCacheKey(t), s = this.getCache(i);
    (!(s != null && s.attributeMap) || Object.keys(s == null ? void 0 : s.attributeMap).length === 0) && (t.lastUpdateTime = void 0);
    const n = await this.mGatewayAPIUtil.authRequest(mn.USER_ENTITY_GET, t), a = n == null ? void 0 : n.data;
    if (a) {
      const o = Object.assign({}, s == null ? void 0 : s.attributeMap, a == null ? void 0 : a.attributeMap);
      a.attributeMap = o;
    }
    return Object.assign({}, s, a);
  }
}
class oT {
  constructor() {
    y(this, "TAG", "UserEntityMgr");
    y(this, "mUserEntityMgrBase");
    this.mUserEntityMgrBase = new aT(this.TAG);
  }
  /**
   * 获指定ID配置
   *
   * @param entityEnum -
   */
  getUserEntity(e) {
    return this.mUserEntityMgrBase.getUserEntity(e);
  }
  /**
   * 获取用户所有配置
   *
   */
  getUserAllEntities() {
    const e = Object.values(_d).filter((t) => !isNaN(Number(t)));
    return this.getUserEntities(e);
  }
  /**
   * 获取用户所有配置
   *
   * @param listener
   */
  getUserEntities(e) {
    return this.mUserEntityMgrBase.getUserEntities(e);
  }
}
const lT = new oT(), cT = "Account";
let oc = !1;
async function Pn(r) {
  var s;
  const e = r.accountType == ji.THIRD_LOGIN ? mn.ACCOUNT_THIRD_LOGIN : mn.USER_LOGIN;
  r.country = (s = re.country) == null ? void 0 : s.domainAbbreviation, S.d(cT, "login coutry", re.country);
  const i = (await Ae.noAuthRequest(e, r)).data;
  return i.changeRegion === 1 ? (i.regionGatewayDomain && (Je.gatewayDomain = i.regionGatewayDomain), i.regionId && (Je.regionId = i.regionId), i.regionGatewayProtocol && (Je.gatewayProtocol = i.regionGatewayProtocol), Pn(r)) : (k1(i), i);
}
function dT(r, e) {
  const i = {
    accountType: P1(r) ? ji.EMAIL : ji.MOBILE,
    account: r,
    password: nT(e),
    pwdType: Os.PASSWORD
  };
  return Pn(i);
}
function hT(r, e) {
  const t = P1(r), i = t ? ji.EMAIL : ji.MOBILE, s = t ? Os.EMAIL_CODE : Os.MOBILE_CODE;
  return Pn({
    accountType: i,
    account: r,
    password: e,
    pwdType: s
  });
}
function uT(r) {
  const e = {
    accountType: ji.ONE_KEY,
    account: "",
    password: r,
    pwdType: Os.AUTH2_CODE
  };
  return Pn(e);
}
function fT(r) {
  const e = {
    accountType: ji.THIRD_LOGIN,
    account: "",
    password: r,
    pwdType: Os.AUTH2_CODE
  };
  return Pn(e);
}
function pT(r, e, t, i) {
  let s = t, n = i || Date.now() + 3 * 24 * 3600 * 1e3;
  try {
    const a = e.split("."), o = JSON.parse(atob(a[1])), { uid: c, exp: l, regionId: d } = o;
    s = c, n = l * 1e3, d > -1 && (Je.regionId = d), Pm(r);
  } catch {
  } finally {
    k1({
      accessToken: e,
      userId: s || 0,
      accessTokenExpireTime: n
    });
  }
}
function k1(r) {
  oc = !1, Gm(), wi.setUserToken(r.accessToken), wi.setUserId(r.userId), wi.setTokenExpiredTime(r.accessTokenExpireTime), lT.getUserAllEntities(), mT();
}
async function mT() {
}
async function gT() {
  oc = !0, Ae.authRequest(mn.ACCOUNT_LOGOUT).finally(() => {
    oc && (wi.clear(), Gm());
  });
}
function _T(r) {
  I2(r);
}
const y6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  loginByAuth2: fT,
  loginByOneKey: uT,
  loginByPassword: dT,
  loginByToken: pT,
  loginByVerifyCode: hT,
  logout: gT,
  setOnTokenInvalidListener: _T
}, Symbol.toStringTag, { value: "Module" })), yT = "DevicShareeMgr";
async function xT(r, e) {
  if (S.i(yT, `generateShareQrCode iotIdList=${r.length} permissionList=${e}`), !(r != null && r.length))
    throw new Lt("iotIdList is empty");
  if (!(e != null && e.length))
    throw new Lt("permissionList is empty");
  const t = { iotIdList: r, permissionList: e };
  return (await Ae.authRequest(vt.GENERATE_SHARE_QRCODE, t)).data;
}
async function vT(r) {
  const e = { qrKey: r };
  return (await Ae.authRequest(vt.SCAN_BIND_BY_SHARE_QRCODE, e)).data;
}
async function ET(r) {
  return (await Ae.authRequest(vt.SHARE_DEVICE_TO_USER, r)).data;
}
async function ST(r) {
  const e = { recordIdList: r };
  await Ae.authRequest(vt.OWNER_CANCEL_SHARE, e);
}
async function TT(r, e) {
  const t = {
    recordIdList: r,
    agree: e
  };
  await Ae.authRequest(vt.CONFIRM_SHARE, t);
}
async function bT(r) {
  return (await Ae.authRequest(vt.GET_SHARE_NOTICE_LIST, r)).data;
}
async function AT(r) {
  return (await Ae.authRequest(vt.QUERY_SHARE_RECORD_BY_BATCH, r)).data;
}
async function CT(r, e) {
  const t = {
    recordId: r,
    permissionList: e
  };
  await Ae.authRequest(vt.SHARE_PERMISSION_SET, t);
}
async function RT(r) {
  return (await Ae.authRequest(vt.GET_SHARED_USERS, r)).data;
}
async function IT(r) {
  return (await Ae.authRequest(vt.GET_SHARED_COUNT, r)).data;
}
const x6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  cancelShare: ST,
  confirmShare: TT,
  generateShareQrCode: xT,
  getShareNoticeList: bT,
  getSharedCountList: IT,
  getSharedUserList: RT,
  queryShareRecordByBatch: AT,
  scanBindByShareQrcode: vT,
  setSharePermission: CT,
  shareDevices: ET
}, Symbol.toStringTag, { value: "Module" })), ar = "BaseRegionManager";
function Ei(r) {
  var t;
  const e = (t = r == null ? void 0 : r.serviceAddresses) == null ? void 0 : t[gs.GATEWAY];
  return e || S.e(ar, "getGatewayHost failed, use default gateway", r), e;
}
class LT {
  async getRegionList(e, t, i) {
    const s = {
      iotId: e,
      beginTime: t,
      endTime: i,
      serviceNameList: [gs.GATEWAY],
      origin: null
    }, n = await this.regionHistoryCache.request(s, !1);
    if (n == null) {
      S.e(ar, "getRegionList, region list is null");
      return;
    }
    const a = n.data, o = a == null ? void 0 : a.regionList;
    if (!(o != null && o.length)) {
      S.w(ar, "empty region list");
      return;
    }
    return o;
  }
  async getAllRegion(e = !1) {
    const t = {
      serviceNameList: [gs.GATEWAY]
    }, i = await this.regionAllCache.request(t, e), s = i == null ? void 0 : i.data;
    return s == null ? void 0 : s.regionList;
  }
  async getTargetRegion(e) {
    let t = await this.getAllRegion(), i = t == null ? void 0 : t.filter((s) => {
      s.region == e;
    });
    return i != null && i.length || (t = await this.getAllRegion(!0), i = t == null ? void 0 : t.filter((s) => {
      s.region == e;
    })), i == null ? void 0 : i.filter((s) => {
      Ei(s) != null;
    });
  }
  async getCurrentRegion(e, t) {
    var i = void 0;
    return t || (i = await this.getTargetRegion(t)), i != null && i.length || (i = await this.getRegionListByTime(e, -1)), i == null ? void 0 : i[0];
  }
  async getRegionListByTime(e, t) {
    return this.getRegionListByTimeRange(e, t, t);
  }
  async getRegionListByTimeRange(e, t, i) {
    var d;
    if (t > i) {
      S.e(ar, "getRegionListByTime, input start end time illegal, start=[$beginTime], end=[$endTime]");
      return;
    }
    const s = Date.now(), n = s - 3600 * 24 * 1e3 * 30 * 6, a = (d = await this.getRegionList(e, n, s)) == null ? void 0 : d.filter((h) => Ei(h));
    if (!(a != null && a.length)) {
      S.e(ar, "getRegionListByTime, region list is null");
      return;
    }
    const o = Date.now(), c = [], l = i > o ? o : i;
    return t == -1 ? (c.push({ ...a[0], startTime: t, endTime: l }), c) : (a.forEach((h) => {
      const u = h.startTime;
      var f = h.endTime;
      if (f == null && (f = o), u <= l && l <= f || u <= t && t <= f || t <= u && u <= l || t <= f && f <= l) {
        const p = { ...h, endTime: f };
        p.startTime < t && (p.startTime = t), p.endTime > l && (p.endTime = l), c.push(p);
      }
    }), S.d(ar, "getRegionListByTime, resultList=", c), c);
  }
}
class DT {
  constructor(e, t, i) {
    y(this, "TAG", "CloudPlaybackMgr");
    y(this, "mRegionManager");
    y(this, "mHttpCloudPlayback");
    this.TAG = e, this.mRegionManager = t, this.mHttpCloudPlayback = i;
  }
  /**
   * 查询录制列表
   *
   * @param params [RecordQueryReq]
   * @param listener [OnResultListener]<[RecordQueryRsp]>
   */
  async recordQuery(e) {
    var c;
    const t = e.pageSize;
    let i = e.beginTime, s = e.endTime;
    const n = await this.mRegionManager.getRegionListByTimeRange(e.iotId, i, s);
    if (!(n != null && n.length))
      throw S.e(this.TAG, "recordQuery Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const a = {
      recordFileList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let o;
    for (let l = 0; l < n.length; l++) {
      const d = n[l];
      s = d.endTime, i = d.startTime;
      do {
        const h = {
          iotId: e.iotId,
          beginTime: i,
          endTime: s,
          pageSize: Math.min(t - a.recordFileList.length, 100)
        }, u = Ei(d);
        if (u && (o = await this.mHttpCloudPlayback.recordQuery(u.protocol, u.domain, h)), !o || (a.recordFileList.push(...o.recordFileList), a.nextValid = o.nextValid, a.recordFileList.length >= t))
          break;
        s = o.nextEndTime ?? 0, s > 0 && s--;
      } while (o != null && o.nextValid && s > 0);
    }
    if (a.recordFileList.length ? a.nextEndTime = i : a.nextEndTime = Math.max(((c = a.recordFileList.at(-1)) == null ? void 0 : c.beginTime) ?? 0, i), !a.recordFileList.length && !o)
      throw new ur("timeline record response error");
    return a;
  }
  /**
   * 获取录制播放地址
   *
   * @param vodUrlGetReq [VodUrlGetReq]
   * @param listener [OnResultListener]<[VodUrlRsp]>
   */
  async getVodPlayUrl(e) {
    const t = await this.mRegionManager.getRegionListByTimeRange(e.iotId, e.beginTime, e.endTime);
    if (!(t != null && t.length))
      throw S.e(this.TAG, "getVodPlayUrl Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const i = t.at(-1), s = Ei(i);
    if (s) {
      const n = await this.mHttpCloudPlayback.getVodPlayUrl(s == null ? void 0 : s.protocol, s == null ? void 0 : s.domain, e);
      if (n)
        return n;
    }
    throw new ur("vod play url response error");
  }
  /**
   * 查询录制统计
   *
   * @param monthQueryReq [MonthQueryReq]
   */
  async monthRecordQuery(e) {
    return this.monthQuery(0, e);
  }
  /**
   * Month query
   *
   * @param type 0: 录制 1：事件 2：消息
   * @param monthQueryReq
   * @param listener
   */
  async monthQuery(e, t) {
    const i = await this.mRegionManager.getRegionListByTimeRange(t.iotId, t.beginTime, t.endTime);
    if (!(i != null && i.length))
      throw S.e(this.TAG, "type=$type monthQuery Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const s = i.map(async (l) => {
      const d = Ei(l), h = {
        iotId: t.iotId,
        beginTime: l.startTime,
        endTime: l.endTime,
        zoneOffsetId: t.zoneOffsetId
      };
      if (d)
        switch (e) {
          case 0:
            return this.mHttpCloudPlayback.monthRecordQuery(d.protocol, d.domain, h);
          case 1:
            return this.mHttpCloudPlayback.monthEventQuery(d.protocol, d.domain, h);
          default:
            return this.mHttpCloudPlayback.msgCenterMonthEventQuery(d == null ? void 0 : d.protocol, d == null ? void 0 : d.domain, h);
        }
    }), n = await Promise.all(s), a = {};
    return n.forEach((l) => {
      const d = l == null ? void 0 : l.dayCntList;
      d && d.forEach((h) => {
        a[h.dateStr] ? a[h.dateStr] = a[h.dateStr] + h.count : a[h.dateStr] = h.count;
      });
    }), {
      dayCntList: Object.entries(a).map(([l, d]) => ({ dateStr: l, count: d }))
    };
  }
  /**
   * 录制删除
   *
   * @param recordDeleteReq [RecordDeleteReq]
   */
  async recordDelete(e) {
    const t = await this.mRegionManager.getRegionListByTimeRange(e.iotId, e.beginTime, e.endTime);
    if (!(t != null && t.length))
      throw S.e(this.TAG, "recordDelete Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const i = t.map(async (n) => {
      const a = Ei(n);
      if (!a) return;
      const o = {
        iotId: e.iotId,
        beginTime: n.startTime,
        endTime: n.endTime
      };
      return this.mHttpCloudPlayback.recordDelete(a.protocol, a.domain, o);
    });
    return (await Promise.all(i))[0];
  }
  /**
   * 查询录制事件
   *
   * @param params [EventQueryReq]
   * @param listener [OnResultListener]<[EventQueryRsp]>
   */
  async eventQuery(e) {
    var c;
    const t = e.pageSize;
    let i = e.beginTime, s = e.endTime;
    const n = await this.mRegionManager.getRegionListByTimeRange(e.iotId, i, s);
    if (!(n != null && n.length))
      throw S.w(this.TAG, "queryEventList Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const a = {
      eventList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let o;
    for (let l = 0; l < n.length; l++) {
      const d = n[l];
      s = d.endTime, i = d.startTime;
      do {
        const h = {
          iotId: e.iotId,
          beginTime: i,
          endTime: s,
          pageSize: Math.min(t - a.eventList.length, 100)
        };
        h.eventTypes = e.eventTypes;
        const u = Ei(d);
        if (u && (o = await this.mHttpCloudPlayback.eventQuery(u == null ? void 0 : u.protocol, u == null ? void 0 : u.domain, h)), o == null || (a.eventList.push(...o.eventList), a.nextValid = o.nextValid, a.eventList.length >= t))
          break;
        i = Math.max(i, d.startTime), s = o.nextEndTime ?? 0, s > 0 && s--;
      } while (o != null && o.nextValid && s > 0);
    }
    if (a.eventList.length ? a.nextEndTime = Math.max(((c = a.eventList.at(-1)) == null ? void 0 : c.beginTime) ?? 0, i) : a.nextEndTime = i, !a.eventList.length && !o)
      throw new ur("timeline event response error");
    return a;
  }
  /**
   * 查询事件统计
   *
   * @param monthQueryReq [MonthQueryReq]
   * @param listener  [OnResultListener]<[MonthQueryRsp]>
   */
  async monthEventQuery(e) {
    return this.monthQuery(1, e);
  }
  async batchDeleteByRegion(e, t, i) {
    if (!t.eventIds.length)
      throw new Lt(`[${this.TAG}]batchDeleteByRegion:${e}:${i}:` + JSON.stringify(t));
    const s = {};
    t.eventIds.forEach(async (o) => {
      var d;
      var c = i ? void 0 : await this.mRegionManager.getTargetRegion(i);
      if (c != null && c.length || (c = await this.mRegionManager.getRegionListByTime(t.iotId, o)), !(c != null && c.length))
        throw S.e(this.TAG, `type=${e} batchDelete Selected time not in regions: ${o}`), new Lt(`[${this.TAG}]not find device region`);
      const l = Ei(c[0]);
      if (l) {
        const h = l.protocol + "|" + l.domain;
        s[h] || (s[h] = []), (d = s[h]) == null || d.push(o);
      }
    });
    const n = Object.entries(s).map(async ([o, c]) => {
      const [l, d] = o.split("|"), h = l, u = {
        ...t,
        eventIds: c
      };
      return e == 0 ? await this.mHttpCloudPlayback.eventBatchDelete(h, d, u) : await this.mHttpCloudPlayback.msgBatchDelete(h, d, u);
    });
    return (await Promise.all(n))[0];
  }
  /**
   * 批量删除
   *
   * @param type 0:事件 1：消息
   * @param iotId
   * @param eventList
   * @param listener
   */
  async batchDelete(e, t, i) {
    if (!i.length)
      throw new Lt(`[${this.TAG}]batchDelete:${e}:${t}:eventList=` + JSON.stringify(i));
    const s = {};
    i.forEach((o) => {
      var d;
      const c = o.lensId ?? -1, l = o.region ?? "";
      s[c] || (s[c] = {}), s[c][l] || (s[c][l] = []), (d = s[c][l]) == null || d.push(o.eventId);
    });
    const n = Object.entries(s).map(([o, c]) => {
      const l = Number(o), d = l < 0 ? void 0 : l;
      return Object.entries(c).map(async ([h, u]) => {
        const f = {
          iotId: t,
          eventIds: u,
          lensId: d
        };
        return this.batchDeleteByRegion(e, f, h);
      });
    }).flat();
    return (await Promise.all(n))[0];
  }
  /**
   * 事件批量删除
   *
   * @param iotId  设备ID
   * @param eventList TimelineEventInfo[]
   */
  async eventBatchDelete(e, t) {
    return this.batchDelete(0, e, t);
  }
  /**
   * 消息列表（消息中心）
   *
   * @param params [EventQueryReq]
   */
  async msgCenterEventQuery(e) {
    var c;
    const t = e.pageSize;
    let i = e.beginTime, s = e.endTime;
    const n = await this.mRegionManager.getRegionListByTimeRange(e.iotId, i, s);
    if (!(n != null && n.length))
      throw S.w(this.TAG, "allEventQuery Selected time not in regions"), new Lt(`[${this.TAG}]not find device region`);
    const a = {
      eventList: [],
      nextValid: !1,
      nextEndTime: i
    };
    let o;
    for (let l = 0; l < n.length; l++) {
      const d = n[l];
      s = d.endTime, i = d.startTime;
      do {
        const h = {
          iotId: e.iotId,
          beginTime: i,
          endTime: s,
          pageSize: Math.min(t - a.eventList.length, 100)
        };
        h.eventTypes = e.eventTypes;
        const u = Ei(d);
        if (u && (o = await this.mHttpCloudPlayback.msgCenterEventQuery(u.protocol, u.domain, h)), !o || (a.eventList.push(...o.eventList), a.nextValid = o.nextValid, a.eventList.length >= t))
          break;
        i = Math.max(i, d.startTime), s = o.nextEndTime ?? 0, s > 0 && s--;
      } while (o != null && o.nextValid && s > 0);
    }
    if (a.eventList.length ? a.nextEndTime = Math.max(((c = a.eventList.at(-1)) == null ? void 0 : c.beginTime) ?? 0, i) : a.nextEndTime = i, !a.eventList.length && !o)
      throw new ur("msgCenterEventQuery response error");
    return a;
  }
  /**
   * 消息查询统计
   *
   * @param monthQueryReq [MonthQueryReq]
   */
  async msgEventMonthQuery(e) {
    return this.monthQuery(2, e);
  }
  /**
   * Get device desc
   *
   * @param type 0：事件 1：消息
   * @param descReq
   */
  async getDeviceDesc(e, t) {
    const i = Date.now(), s = await this.mRegionManager.getRegionListByTimeRange(t.iotId, i - 24 * 3600 * 1e3, i);
    if (!(s != null && s.length))
      throw S.e(this.TAG, `type=${e} getDeviceDesc Selected time not in regions`), new Lt(`[${this.TAG}]not find device region`);
    const n = s.map((c) => {
      const l = Ei(c);
      if (l)
        return e == 0 ? this.mHttpCloudPlayback.deviceEventDesc(l == null ? void 0 : l.protocol, l == null ? void 0 : l.domain, t) : this.mHttpCloudPlayback.deviceMsgDesc(l == null ? void 0 : l.protocol, l == null ? void 0 : l.domain, t);
    }), a = { latestBeginTime: 0 };
    return (await Promise.all(n)).find((c) => {
    }) ?? a;
  }
  /**
   * 获取设备事件描述（查最新一条数据时间，做显示小红点使用）
   *
   * @param descReq
   */
  async getDeviceEventDesc(e) {
    return this.getDeviceDesc(0, e);
  }
  /**
   * 获取设备消息描述（查最新一条数据时间，做显示小红点使用）
   *
   * @param descReq [DeviceMsgDescReq]
   * @param listener [OnResultListener]<[DeviceDescRsp]>
   */
  async getDeviceMsgDesc(e) {
    return this.getDeviceDesc(0, e);
  }
  /**
   * 消息批量删除
   *
   * @param iotId  设备ID
   * @param eventList List<[TimelineEventInfo]>
   * @param listener [OnResultListener]<Any?>
   */
  async msgBatchDelete(e, t) {
    return this.batchDelete(1, e, t);
  }
}
var ni = /* @__PURE__ */ ((r) => (r.RECORD_QUERY = "/client/vision/customer/record/query", r.GET_VOD_PLAY_URL = "/client/vision/customer/vod/geturl", r.MONTH_RECORD_QUERY = "/client/vision/customer/monthrecord/query", r.EVENT_QUERY = "/client/vision/customer/event/query", r.GET_EVENT_PLAY_URL = "/client/vision/customer/vod/event/geturl", r.MONTH_EVENT_QUERY = "/client/vision/customer/monthevent/query", r.RECORD_DELETE = "/client/vision/customer/record/delete", r.EVENT_BATCH_DELETE = "/client/vision/customer/event/batchdelete", r.MSG_CENTER_EVENT_QUERY = "/client/vision/customer/message/center/event/query", r.MSG_CENTER_MONTH_EVENT_QUERY = "/client/vision/customer/month/message/center/query", r.DEVICE_EVENT_DESC = "/client/vision/customer/event/desc", r.DEVICE_MSG_DESC = "/client/vision/customer/message/center/desc", r.DEVICE_MSG_BATCH_DELETE = "/client/vision/customer/message/center/batchdelete", r.GET_PICTURE_BY_ID = "/client/vision/customer/picture/querybyids", r))(ni || {});
class PT {
  constructor(e, t) {
    y(this, "mGatewayAPIUtil");
    y(this, "mVideoRecordAPI");
    this.mGatewayAPIUtil = e, this.mVideoRecordAPI = t;
  }
  async recordQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, this.mVideoRecordAPI.RECORD_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async getVodPlayUrl(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, this.mVideoRecordAPI.GET_VOD_PLAY_URL, i);
    return s == null ? void 0 : s.data;
  }
  async monthRecordQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, this.mVideoRecordAPI.MONTH_RECORD_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async recordDelete(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, this.mVideoRecordAPI.RECORD_DELETE, i);
    return s == null ? void 0 : s.data;
  }
  async eventQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.EVENT_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async msgCenterEventQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.MSG_CENTER_EVENT_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async msgCenterMonthEventQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.MSG_CENTER_MONTH_EVENT_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async deviceEventDesc(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.DEVICE_EVENT_DESC, i);
    return s == null ? void 0 : s.data;
  }
  async deviceMsgDesc(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.DEVICE_MSG_DESC, i);
    return s == null ? void 0 : s.data;
  }
  async msgBatchDelete(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.DEVICE_MSG_BATCH_DELETE, i);
    return s == null ? void 0 : s.data;
  }
  async monthEventQuery(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.MONTH_EVENT_QUERY, i);
    return s == null ? void 0 : s.data;
  }
  async eventBatchDelete(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.EVENT_BATCH_DELETE, i);
    return s == null ? void 0 : s.data;
  }
  async getPictureById(e, t, i) {
    const s = await this.mGatewayAPIUtil.authRequestWithHost(e, t, ni.GET_PICTURE_BY_ID, i);
    return s == null ? void 0 : s.data;
  }
}
const kT = ni, wT = new PT(Ae, kT);
var yd = /* @__PURE__ */ ((r) => (r.REGION_HISTORY = "/client/thing/region/history", r.CURRENT_REGION = "/client/thing/region/current", r.REGION_ALL = "/client/region/all", r))(yd || {});
class MT extends zi {
  constructor() {
    super(Ts.CACHE_FIRST, void 0, 15 * 1e3);
    y(this, "newTag", "RegionHistoryCache");
  }
  async getCacheKey(t) {
    return t.iotId;
  }
  async doRequest(t) {
    return Ae.authRequest(yd.REGION_HISTORY, t, 3);
  }
}
class BT extends zi {
  constructor() {
    super(Ts.CACHE_FIRST, void 0, 5 * 60 * 1e3);
    y(this, "newTag", "RegionAllCache");
  }
  async getCacheKey() {
    return this.newTag;
  }
  async doRequest(t) {
    return Ae.authRequest(yd.REGION_ALL, t);
  }
}
class FT extends LT {
  constructor() {
    super(...arguments);
    y(this, "TAG", "RegionManager");
    y(this, "regionHistoryCache", new MT());
    y(this, "regionAllCache", new BT());
  }
}
const OT = new FT(), NT = "CloudPlayback", Jt = new DT(NT, OT, wT);
function GT(r) {
  return Jt.recordQuery(r);
}
function w1(r) {
  return Jt.getVodPlayUrl(r);
}
function UT(r) {
  return Jt.monthRecordQuery(r);
}
function VT(r) {
  return Jt.recordDelete(r);
}
function WT(r) {
  return Jt.eventQuery(r);
}
function HT(r) {
  return Jt.monthEventQuery(r);
}
function ZT(r, e) {
  return Jt.eventBatchDelete(r, e);
}
function $T(r) {
  return Jt.msgCenterEventQuery(r);
}
function KT(r) {
  return Jt.msgEventMonthQuery(r);
}
function XT(r) {
  return Jt.getDeviceEventDesc(r);
}
function YT(r) {
  return Jt.getDeviceMsgDesc(r);
}
function zT(r, e) {
  return Jt.msgBatchDelete(r, e);
}
const v6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  eventBatchDelete: ZT,
  eventQuery: WT,
  getDeviceEventDesc: XT,
  getDeviceMsgDesc: YT,
  getVodPlayUrl: w1,
  monthEventQuery: HT,
  monthRecordQuery: UT,
  msgBatchDelete: zT,
  msgCenterEventQuery: $T,
  msgEventMonthQuery: KT,
  recordDelete: VT,
  recordQuery: GT
}, Symbol.toStringTag, { value: "Module" }));
var M1 = /* @__PURE__ */ ((r) => (r[r.UNKNOWN = -999] = "UNKNOWN", r[r.CUSTOM_MSG = -128] = "CUSTOM_MSG", r[r.INTELLIGENT_ALARM = 0] = "INTELLIGENT_ALARM", r[r.MOVING_CHECK = 1] = "MOVING_CHECK", r[r.SOUND_CHECK = 2] = "SOUND_CHECK", r[r.HUMAN_CHECK = 3] = "HUMAN_CHECK", r[r.PET_CHECK = 4] = "PET_CHECK", r[r.CROSS_LINE = 5] = "CROSS_LINE", r[r.REGIONAL_INVASION = 6] = "REGIONAL_INVASION", r[r.FALL_CHECK = 7] = "FALL_CHECK", r[r.FACE_CHECK = 8] = "FACE_CHECK", r))(M1 || {});
const E6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  EventTypeEnum: M1
}, Symbol.toStringTag, { value: "Module" }));
class jT {
  constructor(e, t, i) {
    y(this, "proto");
    y(this, "ip");
    y(this, "port", 80);
    this.proto = e, this.ip = t, this.port = i;
  }
}
const S6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  SignalAddressInfo: jT
}, Symbol.toStringTag, { value: "Module" }));
var Ri = /* @__PURE__ */ ((r) => (r[r.Main = 0] = "Main", r[r.Sub = 1] = "Sub", r))(Ri || {}), ae = /* @__PURE__ */ ((r) => (r.NONE = "NONE", r.PCM = "PCM", r.PCMA = "PCMA", r.PCMU = "PCMU", r.G726 = "G726", r.G722 = "G722", r.AAC = "AAC", r.OPUS = "opus", r.MP3 = "MP3", r.VORBIS = "VORBIS", r))(ae || {}), de = /* @__PURE__ */ ((r) => (r.NONE = "NONE", r.H264 = "H264", r.H265 = "H265", r.VP8 = "VP8", r.VP9 = "VP9", r.VP10 = "VP10", r.AV1 = "AV1", r))(de || {}), Xa = /* @__PURE__ */ ((r) => (r.setScale = "setScale", r.setRotate = "setRotate", r))(Xa || {}), Ya = /* @__PURE__ */ ((r) => (r.snapshot = "snapshot", r.snapshotZoom = "snapshotZoom", r))(Ya || {}), an = /* @__PURE__ */ ((r) => (r.startTalk = "startTalk", r.stopTalk = "stopTalk", r))(an || {}), fr = /* @__PURE__ */ ((r) => (r.requestPictureInPicture = "requestPictureInPicture", r.pictureInPictureElement = "pictureInPictureElement", r.pictureInPictureEnabled = "pictureInPictureEnabled", r.exitPictureInPicture = "exitPictureInPicture", r))(fr || {}), Li = /* @__PURE__ */ ((r) => (r.SnapshotPlugin = "SnapshotPlugin", r.ZoomPlug = "ZoomPlug", r.TalkPlug = "TalkPlug", r.PictureInPicturePlug = "PictureInPicturePlug", r))(Li || {}), oi = /* @__PURE__ */ ((r) => (r.HLS = "hls", r.FLV = "flv", r.WebRTC = "webrtc", r))(oi || {}), Er = /* @__PURE__ */ ((r) => (r[r.DEVICE = 0] = "DEVICE", r[r.GB_DEVICE = 1] = "GB_DEVICE", r[r.STANDARD = 2] = "STANDARD", r))(Er || {}), xd = /* @__PURE__ */ ((r) => (r[r.TYPE_NORMAL = 0] = "TYPE_NORMAL", r[r.TYPE_SDCARD_FILE = 1] = "TYPE_SDCARD_FILE", r))(xd || {}), Gt = /* @__PURE__ */ ((r) => (r.inited = "inited", r.canplay = "canplay", r.ended = "ended", r.error = "error", r.pause = "pause", r.waiting = "waiting", r.playing = "playing", r.timeupdate = "timeupdate", r))(Gt || {});
const T6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AudioEncodeTypeEnum: ae,
  PictureInPicturePluginMethodEnum: fr,
  PlayModeEnum: Er,
  PlayUrlTypeEnum: oi,
  PlayerPluginEnum: Li,
  RTCXWebPlayerEventEnum: Gt,
  SeekTypeEnum: xd,
  SnapshotPluginMethodEnum: Ya,
  StreamTypeEnum: Ri,
  TalkPluginMethodEnum: an,
  VideoEncodeTypeEnum: de,
  ZoomPluginMethodEnum: Xa
}, Symbol.toStringTag, { value: "Module" }));
var lc;
(function(r) {
  r.ERROR = "error", r.LOADING_COMPLETE = "loading_complete", r.RECOVERED_EARLY_EOF = "recovered_early_eof", r.MEDIA_INFO = "media_info", r.METADATA_ARRIVED = "metadata_arrived", r.SCRIPTDATA_ARRIVED = "scriptdata_arrived", r.TIMED_ID3_METADATA_ARRIVED = "timed_id3_metadata_arrived", r.PGS_SUBTITLE_ARRIVED = "pgs_subtitle_arrived", r.SYNCHRONOUS_KLV_METADATA_ARRIVED = "synchronous_klv_metadata_arrived", r.ASYNCHRONOUS_KLV_METADATA_ARRIVED = "asynchronous_klv_metadata_arrived", r.SMPTE2038_METADATA_ARRIVED = "smpte2038_metadata_arrived", r.SCTE35_METADATA_ARRIVED = "scte35_metadata_arrived", r.PES_PRIVATE_DATA_DESCRIPTOR = "pes_private_data_descriptor", r.PES_PRIVATE_DATA_ARRIVED = "pes_private_data_arrived", r.STATISTICS_INFO = "statistics_info", r.DESTROYING = "destroying", r.PLAYER_PAUSE = "pause", r.TIME_UPDATE = "timeupdate", r.CAN_PLAY = "canplay", r.PLAY_ENDED = "ended", r.PLAYING = "playing";
})(lc || (lc = {}));
const z = lc, QT = {
  enableWorker: !1,
  enableWorkerForMSE: !1,
  enableStashBuffer: !0,
  stashInitialSize: void 0,
  isLive: !1,
  liveBufferLatencyChasing: !1,
  liveBufferLatencyChasingOnPaused: !1,
  liveBufferLatencyMaxLatency: 1.5,
  liveBufferLatencyMinRemain: 0.5,
  liveSync: !1,
  liveSyncMaxLatency: 1.2,
  liveSyncTargetLatency: 0.8,
  liveSyncPlaybackRate: 1.2,
  lazyLoad: !0,
  lazyLoadMaxDuration: 3 * 60,
  lazyLoadRecoverDuration: 30,
  deferLoadAfterSourceOpen: !0,
  // autoCleanupSourceBuffer: default as false, leave unspecified
  autoCleanupMaxBackwardDuration: 3 * 60,
  autoCleanupMinBackwardDuration: 2 * 60,
  statisticsInfoReportInterval: 600,
  fixAudioTimestampGap: !0,
  accurateSeek: !1,
  seekType: "range",
  // [range, param, custom]
  seekParamStart: "bstart",
  seekParamEnd: "bend",
  rangeLoadZeroStart: !1,
  customSeekHandler: void 0,
  reuseRedirectedURL: !1,
  // referrerPolicy: leave as unspecified
  headers: void 0,
  customLoader: void 0
};
function Pr() {
  return Object.assign({}, QT);
}
class At {
  constructor(e) {
    this._message = e;
  }
  get name() {
    return "RuntimeException";
  }
  get message() {
    return this._message;
  }
  toString() {
    return this.name + ": " + this.message;
  }
}
class qe extends At {
  constructor(e) {
    super(e);
  }
  get name() {
    return "IllegalStateException";
  }
}
class Yi extends At {
  constructor(e) {
    super(e);
  }
  get name() {
    return "InvalidArgumentException";
  }
}
class Vu extends At {
  constructor(e) {
    super(e);
  }
  get name() {
    return "NotImplementedException";
  }
}
const fe = {
  kIdle: 0,
  kConnecting: 1,
  kBuffering: 2,
  kError: 3,
  kComplete: 4
}, Ue = {
  OK: "OK",
  EXCEPTION: "Exception",
  HTTP_STATUS_CODE_INVALID: "HttpStatusCodeInvalid",
  CONNECTING_TIMEOUT: "ConnectingTimeout",
  EARLY_EOF: "EarlyEof",
  UNRECOVERABLE_EARLY_EOF: "UnrecoverableEarlyEof"
};
class kn {
  constructor(e) {
    this._type = e || "undefined", this._status = fe.kIdle, this._needStash = !1, this._onContentLengthKnown = null, this._onURLRedirect = null, this._onDataArrival = null, this._onError = null, this._onComplete = null;
  }
  destroy() {
    this._status = fe.kIdle, this._onContentLengthKnown = null, this._onURLRedirect = null, this._onDataArrival = null, this._onError = null, this._onComplete = null;
  }
  isWorking() {
    return this._status === fe.kConnecting || this._status === fe.kBuffering;
  }
  get type() {
    return this._type;
  }
  get status() {
    return this._status;
  }
  get needStashBuffer() {
    return this._needStash;
  }
  get onContentLengthKnown() {
    return this._onContentLengthKnown;
  }
  set onContentLengthKnown(e) {
    this._onContentLengthKnown = e;
  }
  get onURLRedirect() {
    return this._onURLRedirect;
  }
  set onURLRedirect(e) {
    this._onURLRedirect = e;
  }
  get onDataArrival() {
    return this._onDataArrival;
  }
  set onDataArrival(e) {
    this._onDataArrival = e;
  }
  get onError() {
    return this._onError;
  }
  set onError(e) {
    this._onError = e;
  }
  get onComplete() {
    return this._onComplete;
  }
  set onComplete(e) {
    this._onComplete = e;
  }
  // pure virtual
  open(e, t) {
    throw new Vu("Unimplemented abstract function!");
  }
  abort() {
    throw new Vu("Unimplemented abstract function!");
  }
}
const Fe = {
  FORMAT_ERROR: "FormatError",
  FORMAT_UNSUPPORTED: "FormatUnsupported",
  CODEC_UNSUPPORTED: "CodecUnsupported"
}, Ai = {
  NETWORK_ERROR: "NetworkError",
  MEDIA_ERROR: "MediaError",
  OTHER_ERROR: "OtherError"
}, xa = {
  NETWORK_EXCEPTION: Ue.EXCEPTION,
  NETWORK_STATUS_CODE_INVALID: Ue.HTTP_STATUS_CODE_INVALID,
  NETWORK_TIMEOUT: Ue.CONNECTING_TIMEOUT,
  NETWORK_UNRECOVERABLE_EARLY_EOF: Ue.UNRECOVERABLE_EARLY_EOF,
  MEDIA_MSE_ERROR: "MediaMSEError",
  MEDIA_FORMAT_ERROR: Fe.FORMAT_ERROR,
  MEDIA_FORMAT_UNSUPPORTED: Fe.FORMAT_UNSUPPORTED,
  MEDIA_CODEC_UNSUPPORTED: Fe.CODEC_UNSUPPORTED
};
let cc, dc;
function JT() {
  cc = console.log, dc = console.error;
}
function Kt(r, ...e) {
  cc && cc(r, ...e);
}
function bs(r, ...e) {
  dc && dc(r, ...e);
}
let qT = class {
  constructor(e) {
    this.listener = {}, this.type = e | "";
  }
  on(e, t) {
    return this.listener[e] || (this.listener[e] = []), this.listener[e].push(t), !0;
  }
  off(e, t) {
    if (this.listener[e]) {
      var i = this.listener[e].indexOf(t);
      return i > -1 && this.listener[e].splice(i, 1), !0;
    }
    return !1;
  }
  offAll() {
    this.listener = {};
  }
  dispatch(e, t) {
    return this.listener[e] ? (this.listener[e].map((i) => {
      i.apply(null, [t]);
    }), !0) : !1;
  }
};
const Ge = {
  WEBRTC_NOT_SUPPORT: "WEBRTC_NOT_SUPPORT",
  WEBRTC_ICE_CANDIDATE_ERROR: "WEBRTC_ICE_CANDIDATE_ERROR",
  WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: "WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED",
  WEBRTC_ON_REMOTE_STREAMS: "WEBRTC_ON_REMOTE_STREAMS",
  WEBRTC_ON_LOCAL_STREAM: "WEBRTC_ON_LOCAL_STREAM",
  WEBRTC_ON_CONNECTION_STATE_CHANGE: "WEBRTC_ON_CONNECTION_STATE_CHANGE",
  WEBRTC_ON_DATA_CHANNEL_OPEN: "WEBRTC_ON_DATA_CHANNEL_OPEN",
  WEBRTC_ON_DATA_CHANNEL_CLOSE: "WEBRTC_ON_DATA_CHANNEL_CLOSE",
  WEBRTC_ON_DATA_CHANNEL_ERR: "WEBRTC_ON_DATA_CHANNEL_ERR",
  WEBRTC_ON_DATA_CHANNEL_MSG: "WEBRTC_ON_DATA_CHANNEL_MSG",
  CAPTURE_STREAM_FAILED: "CAPTURE_STREAM_FAILED"
};
function Wu() {
  return window.navigator.userAgent.match("Firefox") !== null;
}
function eb() {
  return window.navigator.userAgent.match("Chrome") !== null;
}
function tb() {
  return window.navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) !== null;
}
const wt = {
  STREAM: "stream",
  MIC: "mic",
  SCREENCAST: "screen-cast",
  FILE: "file",
  MIXED: "mixed"
}, gt = {
  STREAM: "stream",
  CAMERA: "camera",
  SCREENCAST: "screen-cast",
  FILE: "file",
  MIXED: "mixed"
}, ib = {
  /**
   * Audio tracks.
   * @type string
   */
  AUDIO: "audio",
  /**
   * Video tracks.
   * @type string
   */
  VIDEO: "video",
  /**
   * Both audio and video tracks.
   * @type string
   */
  AUDIO_AND_VIDEO: "av"
};
class B1 {
  // eslint-disable-next-line require-jsdoc
  constructor(e, t) {
    this.width = e, this.height = t;
  }
}
let F1 = !0, O1 = !0;
function jr(r, e, t) {
  const i = r.match(e);
  return i && i.length >= t && parseFloat(i[t], 10);
}
function zs(r, e, t) {
  if (!r.RTCPeerConnection)
    return;
  const i = r.RTCPeerConnection.prototype, s = i.addEventListener;
  i.addEventListener = function(a, o) {
    if (a !== e)
      return s.apply(this, arguments);
    const c = (l) => {
      const d = t(l);
      d && (o.handleEvent ? o.handleEvent(d) : o(d));
    };
    return this._eventMap = this._eventMap || {}, this._eventMap[e] || (this._eventMap[e] = /* @__PURE__ */ new Map()), this._eventMap[e].set(o, c), s.apply(this, [
      a,
      c
    ]);
  };
  const n = i.removeEventListener;
  i.removeEventListener = function(a, o) {
    if (a !== e || !this._eventMap || !this._eventMap[e])
      return n.apply(this, arguments);
    if (!this._eventMap[e].has(o))
      return n.apply(this, arguments);
    const c = this._eventMap[e].get(o);
    return this._eventMap[e].delete(o), this._eventMap[e].size === 0 && delete this._eventMap[e], Object.keys(this._eventMap).length === 0 && delete this._eventMap, n.apply(this, [
      a,
      c
    ]);
  }, Object.defineProperty(i, "on" + e, {
    get() {
      return this["_on" + e];
    },
    set(a) {
      this["_on" + e] && (this.removeEventListener(
        e,
        this["_on" + e]
      ), delete this["_on" + e]), a && this.addEventListener(
        e,
        this["_on" + e] = a
      );
    },
    enumerable: !0,
    configurable: !0
  });
}
function sb(r) {
  return typeof r != "boolean" ? new Error("Argument type: " + typeof r + ". Please use a boolean.") : (F1 = r, r ? "adapter.js logging disabled" : "adapter.js logging enabled");
}
function rb(r) {
  return typeof r != "boolean" ? new Error("Argument type: " + typeof r + ". Please use a boolean.") : (O1 = !r, "adapter.js deprecation warnings " + (r ? "disabled" : "enabled"));
}
function N1() {
  if (typeof window == "object") {
    if (F1)
      return;
    typeof console < "u" && typeof console.log == "function" && console.log.apply(console, arguments);
  }
}
function vd(r, e) {
  O1 && console.warn(r + " is deprecated, please use " + e + " instead.");
}
function nb(r) {
  const e = { browser: null, version: null };
  if (typeof r > "u" || !r.navigator || !r.navigator.userAgent)
    return e.browser = "Not a browser.", e;
  const { navigator: t } = r;
  if (t.userAgentData && t.userAgentData.brands) {
    const i = t.userAgentData.brands.find((s) => s.brand === "Chromium");
    if (i)
      return { browser: "chrome", version: parseInt(i.version, 10) };
  }
  if (t.mozGetUserMedia)
    e.browser = "firefox", e.version = parseInt(jr(
      t.userAgent,
      /Firefox\/(\d+)\./,
      1
    ));
  else if (t.webkitGetUserMedia || r.isSecureContext === !1 && r.webkitRTCPeerConnection)
    e.browser = "chrome", e.version = parseInt(jr(
      t.userAgent,
      /Chrom(e|ium)\/(\d+)\./,
      2
    ));
  else if (r.RTCPeerConnection && t.userAgent.match(/AppleWebKit\/(\d+)\./))
    e.browser = "safari", e.version = parseInt(jr(
      t.userAgent,
      /AppleWebKit\/(\d+)\./,
      1
    )), e.supportsUnifiedPlan = r.RTCRtpTransceiver && "currentDirection" in r.RTCRtpTransceiver.prototype, e._safariVersion = jr(
      t.userAgent,
      /Version\/(\d+(\.?\d+))/,
      1
    );
  else
    return e.browser = "Not a supported browser.", e;
  return e;
}
function Hu(r) {
  return Object.prototype.toString.call(r) === "[object Object]";
}
function G1(r) {
  return Hu(r) ? Object.keys(r).reduce(function(e, t) {
    const i = Hu(r[t]), s = i ? G1(r[t]) : r[t], n = i && !Object.keys(s).length;
    return s === void 0 || n ? e : Object.assign(e, { [t]: s });
  }, {}) : r;
}
function hc(r, e, t) {
  !e || t.has(e.id) || (t.set(e.id, e), Object.keys(e).forEach((i) => {
    i.endsWith("Id") ? hc(r, r.get(e[i]), t) : i.endsWith("Ids") && e[i].forEach((s) => {
      hc(r, r.get(s), t);
    });
  }));
}
function Zu(r, e, t) {
  const i = t ? "outbound-rtp" : "inbound-rtp", s = /* @__PURE__ */ new Map();
  if (e === null)
    return s;
  const n = [];
  return r.forEach((a) => {
    a.type === "track" && a.trackIdentifier === e.id && n.push(a);
  }), n.forEach((a) => {
    r.forEach((o) => {
      o.type === i && o.trackId === a.id && hc(r, o, s);
    });
  }), s;
}
const $u = N1;
function U1(r, e) {
  const t = r && r.navigator;
  if (!t.mediaDevices)
    return;
  const i = function(o) {
    if (typeof o != "object" || o.mandatory || o.optional)
      return o;
    const c = {};
    return Object.keys(o).forEach((l) => {
      if (l === "require" || l === "advanced" || l === "mediaSource")
        return;
      const d = typeof o[l] == "object" ? o[l] : { ideal: o[l] };
      d.exact !== void 0 && typeof d.exact == "number" && (d.min = d.max = d.exact);
      const h = function(u, f) {
        return u ? u + f.charAt(0).toUpperCase() + f.slice(1) : f === "deviceId" ? "sourceId" : f;
      };
      if (d.ideal !== void 0) {
        c.optional = c.optional || [];
        let u = {};
        typeof d.ideal == "number" ? (u[h("min", l)] = d.ideal, c.optional.push(u), u = {}, u[h("max", l)] = d.ideal, c.optional.push(u)) : (u[h("", l)] = d.ideal, c.optional.push(u));
      }
      d.exact !== void 0 && typeof d.exact != "number" ? (c.mandatory = c.mandatory || {}, c.mandatory[h("", l)] = d.exact) : ["min", "max"].forEach((u) => {
        d[u] !== void 0 && (c.mandatory = c.mandatory || {}, c.mandatory[h(u, l)] = d[u]);
      });
    }), o.advanced && (c.optional = (c.optional || []).concat(o.advanced)), c;
  }, s = function(o, c) {
    if (e.version >= 61)
      return c(o);
    if (o = JSON.parse(JSON.stringify(o)), o && typeof o.audio == "object") {
      const l = function(d, h, u) {
        h in d && !(u in d) && (d[u] = d[h], delete d[h]);
      };
      o = JSON.parse(JSON.stringify(o)), l(o.audio, "autoGainControl", "googAutoGainControl"), l(o.audio, "noiseSuppression", "googNoiseSuppression"), o.audio = i(o.audio);
    }
    if (o && typeof o.video == "object") {
      let l = o.video.facingMode;
      l = l && (typeof l == "object" ? l : { ideal: l });
      const d = e.version < 66;
      if (l && (l.exact === "user" || l.exact === "environment" || l.ideal === "user" || l.ideal === "environment") && !(t.mediaDevices.getSupportedConstraints && t.mediaDevices.getSupportedConstraints().facingMode && !d)) {
        delete o.video.facingMode;
        let h;
        if (l.exact === "environment" || l.ideal === "environment" ? h = ["back", "rear"] : (l.exact === "user" || l.ideal === "user") && (h = ["front"]), h)
          return t.mediaDevices.enumerateDevices().then((u) => {
            u = u.filter((p) => p.kind === "videoinput");
            let f = u.find((p) => h.some((m) => p.label.toLowerCase().includes(m)));
            return !f && u.length && h.includes("back") && (f = u[u.length - 1]), f && (o.video.deviceId = l.exact ? { exact: f.deviceId } : { ideal: f.deviceId }), o.video = i(o.video), $u("chrome: " + JSON.stringify(o)), c(o);
          });
      }
      o.video = i(o.video);
    }
    return $u("chrome: " + JSON.stringify(o)), c(o);
  }, n = function(o) {
    return e.version >= 64 ? o : {
      name: {
        PermissionDeniedError: "NotAllowedError",
        PermissionDismissedError: "NotAllowedError",
        InvalidStateError: "NotAllowedError",
        DevicesNotFoundError: "NotFoundError",
        ConstraintNotSatisfiedError: "OverconstrainedError",
        TrackStartError: "NotReadableError",
        MediaDeviceFailedDueToShutdown: "NotAllowedError",
        MediaDeviceKillSwitchOn: "NotAllowedError",
        TabCaptureError: "AbortError",
        ScreenCaptureError: "AbortError",
        DeviceCaptureError: "AbortError"
      }[o.name] || o.name,
      message: o.message,
      constraint: o.constraint || o.constraintName,
      toString() {
        return this.name + (this.message && ": ") + this.message;
      }
    };
  }, a = function(o, c, l) {
    s(o, (d) => {
      t.webkitGetUserMedia(d, c, (h) => {
        l && l(n(h));
      });
    });
  };
  if (t.getUserMedia = a.bind(t), t.mediaDevices.getUserMedia) {
    const o = t.mediaDevices.getUserMedia.bind(t.mediaDevices);
    t.mediaDevices.getUserMedia = function(c) {
      return s(c, (l) => o(l).then((d) => {
        if (l.audio && !d.getAudioTracks().length || l.video && !d.getVideoTracks().length)
          throw d.getTracks().forEach((h) => {
            h.stop();
          }), new DOMException("", "NotFoundError");
        return d;
      }, (d) => Promise.reject(n(d))));
    };
  }
}
function V1(r) {
  r.MediaStream = r.MediaStream || r.webkitMediaStream;
}
function W1(r) {
  if (typeof r == "object" && r.RTCPeerConnection && !("ontrack" in r.RTCPeerConnection.prototype)) {
    Object.defineProperty(r.RTCPeerConnection.prototype, "ontrack", {
      get() {
        return this._ontrack;
      },
      set(t) {
        this._ontrack && this.removeEventListener("track", this._ontrack), this.addEventListener("track", this._ontrack = t);
      },
      enumerable: !0,
      configurable: !0
    });
    const e = r.RTCPeerConnection.prototype.setRemoteDescription;
    r.RTCPeerConnection.prototype.setRemoteDescription = function() {
      return this._ontrackpoly || (this._ontrackpoly = (i) => {
        i.stream.addEventListener("addtrack", (s) => {
          let n;
          r.RTCPeerConnection.prototype.getReceivers ? n = this.getReceivers().find((o) => o.track && o.track.id === s.track.id) : n = { track: s.track };
          const a = new Event("track");
          a.track = s.track, a.receiver = n, a.transceiver = { receiver: n }, a.streams = [i.stream], this.dispatchEvent(a);
        }), i.stream.getTracks().forEach((s) => {
          let n;
          r.RTCPeerConnection.prototype.getReceivers ? n = this.getReceivers().find((o) => o.track && o.track.id === s.id) : n = { track: s };
          const a = new Event("track");
          a.track = s, a.receiver = n, a.transceiver = { receiver: n }, a.streams = [i.stream], this.dispatchEvent(a);
        });
      }, this.addEventListener("addstream", this._ontrackpoly)), e.apply(this, arguments);
    };
  } else
    zs(r, "track", (e) => (e.transceiver || Object.defineProperty(
      e,
      "transceiver",
      { value: { receiver: e.receiver } }
    ), e));
}
function H1(r) {
  if (typeof r == "object" && r.RTCPeerConnection && !("getSenders" in r.RTCPeerConnection.prototype) && "createDTMFSender" in r.RTCPeerConnection.prototype) {
    const e = function(s, n) {
      return {
        track: n,
        get dtmf() {
          return this._dtmf === void 0 && (n.kind === "audio" ? this._dtmf = s.createDTMFSender(n) : this._dtmf = null), this._dtmf;
        },
        _pc: s
      };
    };
    if (!r.RTCPeerConnection.prototype.getSenders) {
      r.RTCPeerConnection.prototype.getSenders = function() {
        return this._senders = this._senders || [], this._senders.slice();
      };
      const s = r.RTCPeerConnection.prototype.addTrack;
      r.RTCPeerConnection.prototype.addTrack = function(o, c) {
        let l = s.apply(this, arguments);
        return l || (l = e(this, o), this._senders.push(l)), l;
      };
      const n = r.RTCPeerConnection.prototype.removeTrack;
      r.RTCPeerConnection.prototype.removeTrack = function(o) {
        n.apply(this, arguments);
        const c = this._senders.indexOf(o);
        c !== -1 && this._senders.splice(c, 1);
      };
    }
    const t = r.RTCPeerConnection.prototype.addStream;
    r.RTCPeerConnection.prototype.addStream = function(n) {
      this._senders = this._senders || [], t.apply(this, [n]), n.getTracks().forEach((a) => {
        this._senders.push(e(this, a));
      });
    };
    const i = r.RTCPeerConnection.prototype.removeStream;
    r.RTCPeerConnection.prototype.removeStream = function(n) {
      this._senders = this._senders || [], i.apply(this, [n]), n.getTracks().forEach((a) => {
        const o = this._senders.find((c) => c.track === a);
        o && this._senders.splice(this._senders.indexOf(o), 1);
      });
    };
  } else if (typeof r == "object" && r.RTCPeerConnection && "getSenders" in r.RTCPeerConnection.prototype && "createDTMFSender" in r.RTCPeerConnection.prototype && r.RTCRtpSender && !("dtmf" in r.RTCRtpSender.prototype)) {
    const e = r.RTCPeerConnection.prototype.getSenders;
    r.RTCPeerConnection.prototype.getSenders = function() {
      const i = e.apply(this, []);
      return i.forEach((s) => s._pc = this), i;
    }, Object.defineProperty(r.RTCRtpSender.prototype, "dtmf", {
      get() {
        return this._dtmf === void 0 && (this.track.kind === "audio" ? this._dtmf = this._pc.createDTMFSender(this.track) : this._dtmf = null), this._dtmf;
      }
    });
  }
}
function Z1(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection && r.RTCRtpSender && r.RTCRtpReceiver))
    return;
  if (!("getStats" in r.RTCRtpSender.prototype)) {
    const t = r.RTCPeerConnection.prototype.getSenders;
    t && (r.RTCPeerConnection.prototype.getSenders = function() {
      const n = t.apply(this, []);
      return n.forEach((a) => a._pc = this), n;
    });
    const i = r.RTCPeerConnection.prototype.addTrack;
    i && (r.RTCPeerConnection.prototype.addTrack = function() {
      const n = i.apply(this, arguments);
      return n._pc = this, n;
    }), r.RTCRtpSender.prototype.getStats = function() {
      const n = this;
      return this._pc.getStats().then((a) => (
        /* Note: this will include stats of all senders that
         *   send a track with the same id as sender.track as
         *   it is not possible to identify the RTCRtpSender.
         */
        Zu(a, n.track, !0)
      ));
    };
  }
  if (!("getStats" in r.RTCRtpReceiver.prototype)) {
    const t = r.RTCPeerConnection.prototype.getReceivers;
    t && (r.RTCPeerConnection.prototype.getReceivers = function() {
      const s = t.apply(this, []);
      return s.forEach((n) => n._pc = this), s;
    }), zs(r, "track", (i) => (i.receiver._pc = i.srcElement, i)), r.RTCRtpReceiver.prototype.getStats = function() {
      const s = this;
      return this._pc.getStats().then((n) => Zu(n, s.track, !1));
    };
  }
  if (!("getStats" in r.RTCRtpSender.prototype && "getStats" in r.RTCRtpReceiver.prototype))
    return;
  const e = r.RTCPeerConnection.prototype.getStats;
  r.RTCPeerConnection.prototype.getStats = function() {
    if (arguments.length > 0 && arguments[0] instanceof r.MediaStreamTrack) {
      const i = arguments[0];
      let s, n, a;
      return this.getSenders().forEach((o) => {
        o.track === i && (s ? a = !0 : s = o);
      }), this.getReceivers().forEach((o) => (o.track === i && (n ? a = !0 : n = o), o.track === i)), a || s && n ? Promise.reject(new DOMException(
        "There are more than one sender or receiver for the track.",
        "InvalidAccessError"
      )) : s ? s.getStats() : n ? n.getStats() : Promise.reject(new DOMException(
        "There is no sender or receiver for the track.",
        "InvalidAccessError"
      ));
    }
    return e.apply(this, arguments);
  };
}
function $1(r) {
  r.RTCPeerConnection.prototype.getLocalStreams = function() {
    return this._shimmedLocalStreams = this._shimmedLocalStreams || {}, Object.keys(this._shimmedLocalStreams).map((a) => this._shimmedLocalStreams[a][0]);
  };
  const e = r.RTCPeerConnection.prototype.addTrack;
  r.RTCPeerConnection.prototype.addTrack = function(a, o) {
    if (!o)
      return e.apply(this, arguments);
    this._shimmedLocalStreams = this._shimmedLocalStreams || {};
    const c = e.apply(this, arguments);
    return this._shimmedLocalStreams[o.id] ? this._shimmedLocalStreams[o.id].indexOf(c) === -1 && this._shimmedLocalStreams[o.id].push(c) : this._shimmedLocalStreams[o.id] = [o, c], c;
  };
  const t = r.RTCPeerConnection.prototype.addStream;
  r.RTCPeerConnection.prototype.addStream = function(a) {
    this._shimmedLocalStreams = this._shimmedLocalStreams || {}, a.getTracks().forEach((l) => {
      if (this.getSenders().find((h) => h.track === l))
        throw new DOMException(
          "Track already exists.",
          "InvalidAccessError"
        );
    });
    const o = this.getSenders();
    t.apply(this, arguments);
    const c = this.getSenders().filter((l) => o.indexOf(l) === -1);
    this._shimmedLocalStreams[a.id] = [a].concat(c);
  };
  const i = r.RTCPeerConnection.prototype.removeStream;
  r.RTCPeerConnection.prototype.removeStream = function(a) {
    return this._shimmedLocalStreams = this._shimmedLocalStreams || {}, delete this._shimmedLocalStreams[a.id], i.apply(this, arguments);
  };
  const s = r.RTCPeerConnection.prototype.removeTrack;
  r.RTCPeerConnection.prototype.removeTrack = function(a) {
    return this._shimmedLocalStreams = this._shimmedLocalStreams || {}, a && Object.keys(this._shimmedLocalStreams).forEach((o) => {
      const c = this._shimmedLocalStreams[o].indexOf(a);
      c !== -1 && this._shimmedLocalStreams[o].splice(c, 1), this._shimmedLocalStreams[o].length === 1 && delete this._shimmedLocalStreams[o];
    }), s.apply(this, arguments);
  };
}
function K1(r, e) {
  if (!r.RTCPeerConnection)
    return;
  if (r.RTCPeerConnection.prototype.addTrack && e.version >= 65)
    return $1(r);
  const t = r.RTCPeerConnection.prototype.getLocalStreams;
  r.RTCPeerConnection.prototype.getLocalStreams = function() {
    const d = t.apply(this);
    return this._reverseStreams = this._reverseStreams || {}, d.map((h) => this._reverseStreams[h.id]);
  };
  const i = r.RTCPeerConnection.prototype.addStream;
  r.RTCPeerConnection.prototype.addStream = function(d) {
    if (this._streams = this._streams || {}, this._reverseStreams = this._reverseStreams || {}, d.getTracks().forEach((h) => {
      if (this.getSenders().find((f) => f.track === h))
        throw new DOMException(
          "Track already exists.",
          "InvalidAccessError"
        );
    }), !this._reverseStreams[d.id]) {
      const h = new r.MediaStream(d.getTracks());
      this._streams[d.id] = h, this._reverseStreams[h.id] = d, d = h;
    }
    i.apply(this, [d]);
  };
  const s = r.RTCPeerConnection.prototype.removeStream;
  r.RTCPeerConnection.prototype.removeStream = function(d) {
    this._streams = this._streams || {}, this._reverseStreams = this._reverseStreams || {}, s.apply(this, [this._streams[d.id] || d]), delete this._reverseStreams[this._streams[d.id] ? this._streams[d.id].id : d.id], delete this._streams[d.id];
  }, r.RTCPeerConnection.prototype.addTrack = function(d, h) {
    if (this.signalingState === "closed")
      throw new DOMException(
        "The RTCPeerConnection's signalingState is 'closed'.",
        "InvalidStateError"
      );
    const u = [].slice.call(arguments, 1);
    if (u.length !== 1 || !u[0].getTracks().find((m) => m === d))
      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((m) => m.track === d))
      throw new DOMException(
        "Track already exists.",
        "InvalidAccessError"
      );
    this._streams = this._streams || {}, this._reverseStreams = this._reverseStreams || {};
    const p = this._streams[h.id];
    if (p)
      p.addTrack(d), Promise.resolve().then(() => {
        this.dispatchEvent(new Event("negotiationneeded"));
      });
    else {
      const m = new r.MediaStream([d]);
      this._streams[h.id] = m, this._reverseStreams[m.id] = h, this.addStream(m);
    }
    return this.getSenders().find((m) => m.track === d);
  };
  function n(l, d) {
    let h = d.sdp;
    return Object.keys(l._reverseStreams || []).forEach((u) => {
      const f = l._reverseStreams[u], p = l._streams[f.id];
      h = h.replace(
        new RegExp(p.id, "g"),
        f.id
      );
    }), new RTCSessionDescription({
      type: d.type,
      sdp: h
    });
  }
  function a(l, d) {
    let h = d.sdp;
    return Object.keys(l._reverseStreams || []).forEach((u) => {
      const f = l._reverseStreams[u], p = l._streams[f.id];
      h = h.replace(
        new RegExp(f.id, "g"),
        p.id
      );
    }), new RTCSessionDescription({
      type: d.type,
      sdp: h
    });
  }
  ["createOffer", "createAnswer"].forEach(function(l) {
    const d = r.RTCPeerConnection.prototype[l], h = { [l]() {
      const u = arguments;
      return arguments.length && typeof arguments[0] == "function" ? d.apply(this, [
        (p) => {
          const m = n(this, p);
          u[0].apply(null, [m]);
        },
        (p) => {
          u[1] && u[1].apply(null, p);
        },
        arguments[2]
      ]) : d.apply(this, arguments).then((p) => n(this, p));
    } };
    r.RTCPeerConnection.prototype[l] = h[l];
  });
  const o = r.RTCPeerConnection.prototype.setLocalDescription;
  r.RTCPeerConnection.prototype.setLocalDescription = function() {
    return !arguments.length || !arguments[0].type ? o.apply(this, arguments) : (arguments[0] = a(this, arguments[0]), o.apply(this, arguments));
  };
  const c = Object.getOwnPropertyDescriptor(
    r.RTCPeerConnection.prototype,
    "localDescription"
  );
  Object.defineProperty(
    r.RTCPeerConnection.prototype,
    "localDescription",
    {
      get() {
        const l = c.get.apply(this);
        return l.type === "" ? l : n(this, l);
      }
    }
  ), r.RTCPeerConnection.prototype.removeTrack = function(d) {
    if (this.signalingState === "closed")
      throw new DOMException(
        "The RTCPeerConnection's signalingState is 'closed'.",
        "InvalidStateError"
      );
    if (!d._pc)
      throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.", "TypeError");
    if (!(d._pc === this))
      throw new DOMException(
        "Sender was not created by this connection.",
        "InvalidAccessError"
      );
    this._streams = this._streams || {};
    let u;
    Object.keys(this._streams).forEach((f) => {
      this._streams[f].getTracks().find((m) => d.track === m) && (u = this._streams[f]);
    }), u && (u.getTracks().length === 1 ? this.removeStream(this._reverseStreams[u.id]) : u.removeTrack(d.track), this.dispatchEvent(new Event("negotiationneeded")));
  };
}
function uc(r, e) {
  !r.RTCPeerConnection && r.webkitRTCPeerConnection && (r.RTCPeerConnection = r.webkitRTCPeerConnection), r.RTCPeerConnection && e.version < 53 && ["setLocalDescription", "setRemoteDescription", "addIceCandidate"].forEach(function(t) {
    const i = r.RTCPeerConnection.prototype[t], s = { [t]() {
      return arguments[0] = new (t === "addIceCandidate" ? r.RTCIceCandidate : r.RTCSessionDescription)(arguments[0]), i.apply(this, arguments);
    } };
    r.RTCPeerConnection.prototype[t] = s[t];
  });
}
function X1(r, e) {
  zs(r, "negotiationneeded", (t) => {
    const i = t.target;
    if (!((e.version < 72 || i.getConfiguration && i.getConfiguration().sdpSemantics === "plan-b") && i.signalingState !== "stable"))
      return t;
  });
}
const Ku = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  fixNegotiationNeeded: X1,
  shimAddTrackRemoveTrack: K1,
  shimAddTrackRemoveTrackWithNative: $1,
  shimGetSendersWithDtmf: H1,
  shimGetUserMedia: U1,
  shimMediaStream: V1,
  shimOnTrack: W1,
  shimPeerConnection: uc,
  shimSenderReceiverGetStats: Z1
}, Symbol.toStringTag, { value: "Module" }));
function Y1(r, e) {
  const t = r && r.navigator, i = r && r.MediaStreamTrack;
  if (t.getUserMedia = function(s, n, a) {
    vd(
      "navigator.getUserMedia",
      "navigator.mediaDevices.getUserMedia"
    ), t.mediaDevices.getUserMedia(s).then(n, a);
  }, !(e.version > 55 && "autoGainControl" in t.mediaDevices.getSupportedConstraints())) {
    const s = function(a, o, c) {
      o in a && !(c in a) && (a[c] = a[o], delete a[o]);
    }, n = t.mediaDevices.getUserMedia.bind(t.mediaDevices);
    if (t.mediaDevices.getUserMedia = function(a) {
      return typeof a == "object" && typeof a.audio == "object" && (a = JSON.parse(JSON.stringify(a)), s(a.audio, "autoGainControl", "mozAutoGainControl"), s(a.audio, "noiseSuppression", "mozNoiseSuppression")), n(a);
    }, i && i.prototype.getSettings) {
      const a = i.prototype.getSettings;
      i.prototype.getSettings = function() {
        const o = a.apply(this, arguments);
        return s(o, "mozAutoGainControl", "autoGainControl"), s(o, "mozNoiseSuppression", "noiseSuppression"), o;
      };
    }
    if (i && i.prototype.applyConstraints) {
      const a = i.prototype.applyConstraints;
      i.prototype.applyConstraints = function(o) {
        return this.kind === "audio" && typeof o == "object" && (o = JSON.parse(JSON.stringify(o)), s(o, "autoGainControl", "mozAutoGainControl"), s(o, "noiseSuppression", "mozNoiseSuppression")), a.apply(this, [o]);
      };
    }
  }
}
function ab(r, e) {
  r.navigator.mediaDevices && "getDisplayMedia" in r.navigator.mediaDevices || r.navigator.mediaDevices && (r.navigator.mediaDevices.getDisplayMedia = function(i) {
    if (!(i && i.video)) {
      const s = new DOMException("getDisplayMedia without video constraints is undefined");
      return s.name = "NotFoundError", s.code = 8, Promise.reject(s);
    }
    return i.video === !0 ? i.video = { mediaSource: e } : i.video.mediaSource = e, r.navigator.mediaDevices.getUserMedia(i);
  });
}
function z1(r) {
  typeof r == "object" && r.RTCTrackEvent && "receiver" in r.RTCTrackEvent.prototype && !("transceiver" in r.RTCTrackEvent.prototype) && Object.defineProperty(r.RTCTrackEvent.prototype, "transceiver", {
    get() {
      return { receiver: this.receiver };
    }
  });
}
function fc(r, e) {
  if (typeof r != "object" || !(r.RTCPeerConnection || r.mozRTCPeerConnection))
    return;
  !r.RTCPeerConnection && r.mozRTCPeerConnection && (r.RTCPeerConnection = r.mozRTCPeerConnection), e.version < 53 && ["setLocalDescription", "setRemoteDescription", "addIceCandidate"].forEach(function(s) {
    const n = r.RTCPeerConnection.prototype[s], a = { [s]() {
      return arguments[0] = new (s === "addIceCandidate" ? r.RTCIceCandidate : r.RTCSessionDescription)(arguments[0]), n.apply(this, arguments);
    } };
    r.RTCPeerConnection.prototype[s] = a[s];
  });
  const t = {
    inboundrtp: "inbound-rtp",
    outboundrtp: "outbound-rtp",
    candidatepair: "candidate-pair",
    localcandidate: "local-candidate",
    remotecandidate: "remote-candidate"
  }, i = r.RTCPeerConnection.prototype.getStats;
  r.RTCPeerConnection.prototype.getStats = function() {
    const [n, a, o] = arguments;
    return i.apply(this, [n || null]).then((c) => {
      if (e.version < 53 && !a)
        try {
          c.forEach((l) => {
            l.type = t[l.type] || l.type;
          });
        } catch (l) {
          if (l.name !== "TypeError")
            throw l;
          c.forEach((d, h) => {
            c.set(h, Object.assign({}, d, {
              type: t[d.type] || d.type
            }));
          });
        }
      return c;
    }).then(a, o);
  };
}
function j1(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection && r.RTCRtpSender) || r.RTCRtpSender && "getStats" in r.RTCRtpSender.prototype)
    return;
  const e = r.RTCPeerConnection.prototype.getSenders;
  e && (r.RTCPeerConnection.prototype.getSenders = function() {
    const s = e.apply(this, []);
    return s.forEach((n) => n._pc = this), s;
  });
  const t = r.RTCPeerConnection.prototype.addTrack;
  t && (r.RTCPeerConnection.prototype.addTrack = function() {
    const s = t.apply(this, arguments);
    return s._pc = this, s;
  }), r.RTCRtpSender.prototype.getStats = function() {
    return this.track ? this._pc.getStats(this.track) : Promise.resolve(/* @__PURE__ */ new Map());
  };
}
function Q1(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection && r.RTCRtpSender) || r.RTCRtpSender && "getStats" in r.RTCRtpReceiver.prototype)
    return;
  const e = r.RTCPeerConnection.prototype.getReceivers;
  e && (r.RTCPeerConnection.prototype.getReceivers = function() {
    const i = e.apply(this, []);
    return i.forEach((s) => s._pc = this), i;
  }), zs(r, "track", (t) => (t.receiver._pc = t.srcElement, t)), r.RTCRtpReceiver.prototype.getStats = function() {
    return this._pc.getStats(this.track);
  };
}
function J1(r) {
  !r.RTCPeerConnection || "removeStream" in r.RTCPeerConnection.prototype || (r.RTCPeerConnection.prototype.removeStream = function(t) {
    vd("removeStream", "removeTrack"), this.getSenders().forEach((i) => {
      i.track && t.getTracks().includes(i.track) && this.removeTrack(i);
    });
  });
}
function q1(r) {
  r.DataChannel && !r.RTCDataChannel && (r.RTCDataChannel = r.DataChannel);
}
function eg(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection))
    return;
  const e = r.RTCPeerConnection.prototype.addTransceiver;
  e && (r.RTCPeerConnection.prototype.addTransceiver = function() {
    this.setParametersPromises = [];
    let i = arguments[1] && arguments[1].sendEncodings;
    i === void 0 && (i = []), i = [...i];
    const s = i.length > 0;
    s && i.forEach((a) => {
      if ("rid" in a && !/^[a-z0-9]{0,16}$/i.test(a.rid))
        throw new TypeError("Invalid RID value provided.");
      if ("scaleResolutionDownBy" in a && !(parseFloat(a.scaleResolutionDownBy) >= 1))
        throw new RangeError("scale_resolution_down_by must be >= 1.0");
      if ("maxFramerate" in a && !(parseFloat(a.maxFramerate) >= 0))
        throw new RangeError("max_framerate must be >= 0.0");
    });
    const n = e.apply(this, arguments);
    if (s) {
      const { sender: a } = n, o = a.getParameters();
      (!("encodings" in o) || // Avoid being fooled by patched getParameters() below.
      o.encodings.length === 1 && Object.keys(o.encodings[0]).length === 0) && (o.encodings = i, a.sendEncodings = i, this.setParametersPromises.push(
        a.setParameters(o).then(() => {
          delete a.sendEncodings;
        }).catch(() => {
          delete a.sendEncodings;
        })
      ));
    }
    return n;
  });
}
function tg(r) {
  if (!(typeof r == "object" && r.RTCRtpSender))
    return;
  const e = r.RTCRtpSender.prototype.getParameters;
  e && (r.RTCRtpSender.prototype.getParameters = function() {
    const i = e.apply(this, arguments);
    return "encodings" in i || (i.encodings = [].concat(this.sendEncodings || [{}])), i;
  });
}
function ig(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection))
    return;
  const e = r.RTCPeerConnection.prototype.createOffer;
  r.RTCPeerConnection.prototype.createOffer = function() {
    return this.setParametersPromises && this.setParametersPromises.length ? Promise.all(this.setParametersPromises).then(() => e.apply(this, arguments)).finally(() => {
      this.setParametersPromises = [];
    }) : e.apply(this, arguments);
  };
}
function sg(r) {
  if (!(typeof r == "object" && r.RTCPeerConnection))
    return;
  const e = r.RTCPeerConnection.prototype.createAnswer;
  r.RTCPeerConnection.prototype.createAnswer = function() {
    return this.setParametersPromises && this.setParametersPromises.length ? Promise.all(this.setParametersPromises).then(() => e.apply(this, arguments)).finally(() => {
      this.setParametersPromises = [];
    }) : e.apply(this, arguments);
  };
}
const Xu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  shimAddTransceiver: eg,
  shimCreateAnswer: sg,
  shimCreateOffer: ig,
  shimGetDisplayMedia: ab,
  shimGetParameters: tg,
  shimGetUserMedia: Y1,
  shimOnTrack: z1,
  shimPeerConnection: fc,
  shimRTCDataChannel: q1,
  shimReceiverGetStats: Q1,
  shimRemoveStream: J1,
  shimSenderGetStats: j1
}, Symbol.toStringTag, { value: "Module" }));
function rg(r) {
  if (!(typeof r != "object" || !r.RTCPeerConnection)) {
    if ("getLocalStreams" in r.RTCPeerConnection.prototype || (r.RTCPeerConnection.prototype.getLocalStreams = function() {
      return this._localStreams || (this._localStreams = []), this._localStreams;
    }), !("addStream" in r.RTCPeerConnection.prototype)) {
      const e = r.RTCPeerConnection.prototype.addTrack;
      r.RTCPeerConnection.prototype.addStream = function(i) {
        this._localStreams || (this._localStreams = []), this._localStreams.includes(i) || this._localStreams.push(i), i.getAudioTracks().forEach((s) => e.call(
          this,
          s,
          i
        )), i.getVideoTracks().forEach((s) => e.call(
          this,
          s,
          i
        ));
      }, r.RTCPeerConnection.prototype.addTrack = function(i, ...s) {
        return s && s.forEach((n) => {
          this._localStreams ? this._localStreams.includes(n) || this._localStreams.push(n) : this._localStreams = [n];
        }), e.apply(this, arguments);
      };
    }
    "removeStream" in r.RTCPeerConnection.prototype || (r.RTCPeerConnection.prototype.removeStream = function(t) {
      this._localStreams || (this._localStreams = []);
      const i = this._localStreams.indexOf(t);
      if (i === -1)
        return;
      this._localStreams.splice(i, 1);
      const s = t.getTracks();
      this.getSenders().forEach((n) => {
        s.includes(n.track) && this.removeTrack(n);
      });
    });
  }
}
function ng(r) {
  if (!(typeof r != "object" || !r.RTCPeerConnection) && ("getRemoteStreams" in r.RTCPeerConnection.prototype || (r.RTCPeerConnection.prototype.getRemoteStreams = function() {
    return this._remoteStreams ? this._remoteStreams : [];
  }), !("onaddstream" in r.RTCPeerConnection.prototype))) {
    Object.defineProperty(r.RTCPeerConnection.prototype, "onaddstream", {
      get() {
        return this._onaddstream;
      },
      set(t) {
        this._onaddstream && (this.removeEventListener("addstream", this._onaddstream), this.removeEventListener("track", this._onaddstreampoly)), this.addEventListener("addstream", this._onaddstream = t), this.addEventListener("track", this._onaddstreampoly = (i) => {
          i.streams.forEach((s) => {
            if (this._remoteStreams || (this._remoteStreams = []), this._remoteStreams.includes(s))
              return;
            this._remoteStreams.push(s);
            const n = new Event("addstream");
            n.stream = s, this.dispatchEvent(n);
          });
        });
      }
    });
    const e = r.RTCPeerConnection.prototype.setRemoteDescription;
    r.RTCPeerConnection.prototype.setRemoteDescription = function() {
      const i = this;
      return this._onaddstreampoly || this.addEventListener("track", this._onaddstreampoly = function(s) {
        s.streams.forEach((n) => {
          if (i._remoteStreams || (i._remoteStreams = []), i._remoteStreams.indexOf(n) >= 0)
            return;
          i._remoteStreams.push(n);
          const a = new Event("addstream");
          a.stream = n, i.dispatchEvent(a);
        });
      }), e.apply(i, arguments);
    };
  }
}
function ag(r) {
  if (typeof r != "object" || !r.RTCPeerConnection)
    return;
  const e = r.RTCPeerConnection.prototype, t = e.createOffer, i = e.createAnswer, s = e.setLocalDescription, n = e.setRemoteDescription, a = e.addIceCandidate;
  e.createOffer = function(l, d) {
    const h = arguments.length >= 2 ? arguments[2] : arguments[0], u = t.apply(this, [h]);
    return d ? (u.then(l, d), Promise.resolve()) : u;
  }, e.createAnswer = function(l, d) {
    const h = arguments.length >= 2 ? arguments[2] : arguments[0], u = i.apply(this, [h]);
    return d ? (u.then(l, d), Promise.resolve()) : u;
  };
  let o = function(c, l, d) {
    const h = s.apply(this, [c]);
    return d ? (h.then(l, d), Promise.resolve()) : h;
  };
  e.setLocalDescription = o, o = function(c, l, d) {
    const h = n.apply(this, [c]);
    return d ? (h.then(l, d), Promise.resolve()) : h;
  }, e.setRemoteDescription = o, o = function(c, l, d) {
    const h = a.apply(this, [c]);
    return d ? (h.then(l, d), Promise.resolve()) : h;
  }, e.addIceCandidate = o;
}
function og(r) {
  const e = r && r.navigator;
  if (e.mediaDevices && e.mediaDevices.getUserMedia) {
    const t = e.mediaDevices, i = t.getUserMedia.bind(t);
    e.mediaDevices.getUserMedia = (s) => i(lg(s));
  }
  !e.getUserMedia && e.mediaDevices && e.mediaDevices.getUserMedia && (e.getUserMedia = (function(i, s, n) {
    e.mediaDevices.getUserMedia(i).then(s, n);
  }).bind(e));
}
function lg(r) {
  return r && r.video !== void 0 ? Object.assign(
    {},
    r,
    { video: G1(r.video) }
  ) : r;
}
function cg(r) {
  if (!r.RTCPeerConnection)
    return;
  const e = r.RTCPeerConnection;
  r.RTCPeerConnection = function(i, s) {
    if (i && i.iceServers) {
      const n = [];
      for (let a = 0; a < i.iceServers.length; a++) {
        let o = i.iceServers[a];
        o.urls === void 0 && o.url ? (vd("RTCIceServer.url", "RTCIceServer.urls"), o = JSON.parse(JSON.stringify(o)), o.urls = o.url, delete o.url, n.push(o)) : n.push(i.iceServers[a]);
      }
      i.iceServers = n;
    }
    return new e(i, s);
  }, r.RTCPeerConnection.prototype = e.prototype, "generateCertificate" in e && Object.defineProperty(r.RTCPeerConnection, "generateCertificate", {
    get() {
      return e.generateCertificate;
    }
  });
}
function dg(r) {
  typeof r == "object" && r.RTCTrackEvent && "receiver" in r.RTCTrackEvent.prototype && !("transceiver" in r.RTCTrackEvent.prototype) && Object.defineProperty(r.RTCTrackEvent.prototype, "transceiver", {
    get() {
      return { receiver: this.receiver };
    }
  });
}
function hg(r) {
  const e = r.RTCPeerConnection.prototype.createOffer;
  r.RTCPeerConnection.prototype.createOffer = function(i) {
    if (i) {
      typeof i.offerToReceiveAudio < "u" && (i.offerToReceiveAudio = !!i.offerToReceiveAudio);
      const s = this.getTransceivers().find((a) => a.receiver.track.kind === "audio");
      i.offerToReceiveAudio === !1 && s ? s.direction === "sendrecv" ? s.setDirection ? s.setDirection("sendonly") : s.direction = "sendonly" : s.direction === "recvonly" && (s.setDirection ? s.setDirection("inactive") : s.direction = "inactive") : i.offerToReceiveAudio === !0 && !s && this.addTransceiver("audio", { direction: "recvonly" }), typeof i.offerToReceiveVideo < "u" && (i.offerToReceiveVideo = !!i.offerToReceiveVideo);
      const n = this.getTransceivers().find((a) => a.receiver.track.kind === "video");
      i.offerToReceiveVideo === !1 && n ? n.direction === "sendrecv" ? n.setDirection ? n.setDirection("sendonly") : n.direction = "sendonly" : n.direction === "recvonly" && (n.setDirection ? n.setDirection("inactive") : n.direction = "inactive") : i.offerToReceiveVideo === !0 && !n && this.addTransceiver("video", { direction: "recvonly" });
    }
    return e.apply(this, arguments);
  };
}
function ug(r) {
  typeof r != "object" || r.AudioContext || (r.AudioContext = r.webkitAudioContext);
}
const Yu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  shimAudioContext: ug,
  shimCallbacksAPI: ag,
  shimConstraints: lg,
  shimCreateOfferLegacy: hg,
  shimGetUserMedia: og,
  shimLocalStreamsAPI: rg,
  shimRTCIceServerUrls: cg,
  shimRemoteStreamsAPI: ng,
  shimTrackEventTransceiver: dg
}, Symbol.toStringTag, { value: "Module" }));
var fg = { exports: {} };
(function(r) {
  const e = {};
  e.generateIdentifier = function() {
    return Math.random().toString(36).substring(2, 12);
  }, e.localCName = e.generateIdentifier(), e.splitLines = function(t) {
    return t.trim().split(`
`).map((i) => i.trim());
  }, e.splitSections = function(t) {
    return t.split(`
m=`).map((s, n) => (n > 0 ? "m=" + s : s).trim() + `\r
`);
  }, e.getDescription = function(t) {
    const i = e.splitSections(t);
    return i && i[0];
  }, e.getMediaSections = function(t) {
    const i = e.splitSections(t);
    return i.shift(), i;
  }, e.matchPrefix = function(t, i) {
    return e.splitLines(t).filter((s) => s.indexOf(i) === 0);
  }, e.parseCandidate = function(t) {
    let i;
    t.indexOf("a=candidate:") === 0 ? i = t.substring(12).split(" ") : i = t.substring(10).split(" ");
    const s = {
      foundation: i[0],
      component: { 1: "rtp", 2: "rtcp" }[i[1]] || i[1],
      protocol: i[2].toLowerCase(),
      priority: parseInt(i[3], 10),
      ip: i[4],
      address: i[4],
      // address is an alias for ip.
      port: parseInt(i[5], 10),
      // skip parts[6] == 'typ'
      type: i[7]
    };
    for (let n = 8; n < i.length; n += 2)
      switch (i[n]) {
        case "raddr":
          s.relatedAddress = i[n + 1];
          break;
        case "rport":
          s.relatedPort = parseInt(i[n + 1], 10);
          break;
        case "tcptype":
          s.tcpType = i[n + 1];
          break;
        case "ufrag":
          s.ufrag = i[n + 1], s.usernameFragment = i[n + 1];
          break;
        default:
          s[i[n]] === void 0 && (s[i[n]] = i[n + 1]);
          break;
      }
    return s;
  }, e.writeCandidate = function(t) {
    const i = [];
    i.push(t.foundation);
    const s = t.component;
    s === "rtp" ? i.push(1) : s === "rtcp" ? i.push(2) : i.push(s), i.push(t.protocol.toUpperCase()), i.push(t.priority), i.push(t.address || t.ip), i.push(t.port);
    const n = t.type;
    return i.push("typ"), i.push(n), n !== "host" && t.relatedAddress && t.relatedPort && (i.push("raddr"), i.push(t.relatedAddress), i.push("rport"), i.push(t.relatedPort)), t.tcpType && t.protocol.toLowerCase() === "tcp" && (i.push("tcptype"), i.push(t.tcpType)), (t.usernameFragment || t.ufrag) && (i.push("ufrag"), i.push(t.usernameFragment || t.ufrag)), "candidate:" + i.join(" ");
  }, e.parseIceOptions = function(t) {
    return t.substring(14).split(" ");
  }, e.parseRtpMap = function(t) {
    let i = t.substring(9).split(" ");
    const s = {
      payloadType: parseInt(i.shift(), 10)
      // was: id
    };
    return i = i[0].split("/"), s.name = i[0], s.clockRate = parseInt(i[1], 10), s.channels = i.length === 3 ? parseInt(i[2], 10) : 1, s.numChannels = s.channels, s;
  }, e.writeRtpMap = function(t) {
    let i = t.payloadType;
    t.preferredPayloadType !== void 0 && (i = t.preferredPayloadType);
    const s = t.channels || t.numChannels || 1;
    return "a=rtpmap:" + i + " " + t.name + "/" + t.clockRate + (s !== 1 ? "/" + s : "") + `\r
`;
  }, e.parseExtmap = function(t) {
    const i = t.substring(9).split(" ");
    return {
      id: parseInt(i[0], 10),
      direction: i[0].indexOf("/") > 0 ? i[0].split("/")[1] : "sendrecv",
      uri: i[1],
      attributes: i.slice(2).join(" ")
    };
  }, e.writeExtmap = function(t) {
    return "a=extmap:" + (t.id || t.preferredId) + (t.direction && t.direction !== "sendrecv" ? "/" + t.direction : "") + " " + t.uri + (t.attributes ? " " + t.attributes : "") + `\r
`;
  }, e.parseFmtp = function(t) {
    const i = {};
    let s;
    const n = t.substring(t.indexOf(" ") + 1).split(";");
    for (let a = 0; a < n.length; a++)
      s = n[a].trim().split("="), i[s[0].trim()] = s[1];
    return i;
  }, e.writeFmtp = function(t) {
    let i = "", s = t.payloadType;
    if (t.preferredPayloadType !== void 0 && (s = t.preferredPayloadType), t.parameters && Object.keys(t.parameters).length) {
      const n = [];
      Object.keys(t.parameters).forEach((a) => {
        t.parameters[a] !== void 0 ? n.push(a + "=" + t.parameters[a]) : n.push(a);
      }), i += "a=fmtp:" + s + " " + n.join(";") + `\r
`;
    }
    return i;
  }, e.parseRtcpFb = function(t) {
    const i = t.substring(t.indexOf(" ") + 1).split(" ");
    return {
      type: i.shift(),
      parameter: i.join(" ")
    };
  }, e.writeRtcpFb = function(t) {
    let i = "", s = t.payloadType;
    return t.preferredPayloadType !== void 0 && (s = t.preferredPayloadType), t.rtcpFeedback && t.rtcpFeedback.length && t.rtcpFeedback.forEach((n) => {
      i += "a=rtcp-fb:" + s + " " + n.type + (n.parameter && n.parameter.length ? " " + n.parameter : "") + `\r
`;
    }), i;
  }, e.parseSsrcMedia = function(t) {
    const i = t.indexOf(" "), s = {
      ssrc: parseInt(t.substring(7, i), 10)
    }, n = t.indexOf(":", i);
    return n > -1 ? (s.attribute = t.substring(i + 1, n), s.value = t.substring(n + 1)) : s.attribute = t.substring(i + 1), s;
  }, e.parseSsrcGroup = function(t) {
    const i = t.substring(13).split(" ");
    return {
      semantics: i.shift(),
      ssrcs: i.map((s) => parseInt(s, 10))
    };
  }, e.getMid = function(t) {
    const i = e.matchPrefix(t, "a=mid:")[0];
    if (i)
      return i.substring(6);
  }, e.parseFingerprint = function(t) {
    const i = t.substring(14).split(" ");
    return {
      algorithm: i[0].toLowerCase(),
      // algorithm is case-sensitive in Edge.
      value: i[1].toUpperCase()
      // the definition is upper-case in RFC 4572.
    };
  }, e.getDtlsParameters = function(t, i) {
    return {
      role: "auto",
      fingerprints: e.matchPrefix(
        t + i,
        "a=fingerprint:"
      ).map(e.parseFingerprint)
    };
  }, e.writeDtlsParameters = function(t, i) {
    let s = "a=setup:" + i + `\r
`;
    return t.fingerprints.forEach((n) => {
      s += "a=fingerprint:" + n.algorithm + " " + n.value + `\r
`;
    }), s;
  }, e.parseCryptoLine = function(t) {
    const i = t.substring(9).split(" ");
    return {
      tag: parseInt(i[0], 10),
      cryptoSuite: i[1],
      keyParams: i[2],
      sessionParams: i.slice(3)
    };
  }, e.writeCryptoLine = function(t) {
    return "a=crypto:" + t.tag + " " + t.cryptoSuite + " " + (typeof t.keyParams == "object" ? e.writeCryptoKeyParams(t.keyParams) : t.keyParams) + (t.sessionParams ? " " + t.sessionParams.join(" ") : "") + `\r
`;
  }, e.parseCryptoKeyParams = function(t) {
    if (t.indexOf("inline:") !== 0)
      return null;
    const i = t.substring(7).split("|");
    return {
      keyMethod: "inline",
      keySalt: i[0],
      lifeTime: i[1],
      mkiValue: i[2] ? i[2].split(":")[0] : void 0,
      mkiLength: i[2] ? i[2].split(":")[1] : void 0
    };
  }, e.writeCryptoKeyParams = function(t) {
    return t.keyMethod + ":" + t.keySalt + (t.lifeTime ? "|" + t.lifeTime : "") + (t.mkiValue && t.mkiLength ? "|" + t.mkiValue + ":" + t.mkiLength : "");
  }, e.getCryptoParameters = function(t, i) {
    return e.matchPrefix(
      t + i,
      "a=crypto:"
    ).map(e.parseCryptoLine);
  }, e.getIceParameters = function(t, i) {
    const s = e.matchPrefix(
      t + i,
      "a=ice-ufrag:"
    )[0], n = e.matchPrefix(
      t + i,
      "a=ice-pwd:"
    )[0];
    return s && n ? {
      usernameFragment: s.substring(12),
      password: n.substring(10)
    } : null;
  }, e.writeIceParameters = function(t) {
    let i = "a=ice-ufrag:" + t.usernameFragment + `\r
a=ice-pwd:` + t.password + `\r
`;
    return t.iceLite && (i += `a=ice-lite\r
`), i;
  }, e.parseRtpParameters = function(t) {
    const i = {
      codecs: [],
      headerExtensions: [],
      fecMechanisms: [],
      rtcp: []
    }, n = e.splitLines(t)[0].split(" ");
    i.profile = n[2];
    for (let o = 3; o < n.length; o++) {
      const c = n[o], l = e.matchPrefix(
        t,
        "a=rtpmap:" + c + " "
      )[0];
      if (l) {
        const d = e.parseRtpMap(l), h = e.matchPrefix(
          t,
          "a=fmtp:" + c + " "
        );
        switch (d.parameters = h.length ? e.parseFmtp(h[0]) : {}, d.rtcpFeedback = e.matchPrefix(
          t,
          "a=rtcp-fb:" + c + " "
        ).map(e.parseRtcpFb), i.codecs.push(d), d.name.toUpperCase()) {
          case "RED":
          case "ULPFEC":
            i.fecMechanisms.push(d.name.toUpperCase());
            break;
        }
      }
    }
    e.matchPrefix(t, "a=extmap:").forEach((o) => {
      i.headerExtensions.push(e.parseExtmap(o));
    });
    const a = e.matchPrefix(t, "a=rtcp-fb:* ").map(e.parseRtcpFb);
    return i.codecs.forEach((o) => {
      a.forEach((c) => {
        o.rtcpFeedback.find((d) => d.type === c.type && d.parameter === c.parameter) || o.rtcpFeedback.push(c);
      });
    }), i;
  }, e.writeRtpDescription = function(t, i) {
    let s = "";
    s += "m=" + t + " ", s += i.codecs.length > 0 ? "9" : "0", s += " " + (i.profile || "UDP/TLS/RTP/SAVPF") + " ", s += i.codecs.map((a) => a.preferredPayloadType !== void 0 ? a.preferredPayloadType : a.payloadType).join(" ") + `\r
`, s += `c=IN IP4 0.0.0.0\r
`, s += `a=rtcp:9 IN IP4 0.0.0.0\r
`, i.codecs.forEach((a) => {
      s += e.writeRtpMap(a), s += e.writeFmtp(a), s += e.writeRtcpFb(a);
    });
    let n = 0;
    return i.codecs.forEach((a) => {
      a.maxptime > n && (n = a.maxptime);
    }), n > 0 && (s += "a=maxptime:" + n + `\r
`), i.headerExtensions && i.headerExtensions.forEach((a) => {
      s += e.writeExtmap(a);
    }), s;
  }, e.parseRtpEncodingParameters = function(t) {
    const i = [], s = e.parseRtpParameters(t), n = s.fecMechanisms.indexOf("RED") !== -1, a = s.fecMechanisms.indexOf("ULPFEC") !== -1, o = e.matchPrefix(t, "a=ssrc:").map((u) => e.parseSsrcMedia(u)).filter((u) => u.attribute === "cname"), c = o.length > 0 && o[0].ssrc;
    let l;
    const d = e.matchPrefix(t, "a=ssrc-group:FID").map((u) => u.substring(17).split(" ").map((p) => parseInt(p, 10)));
    d.length > 0 && d[0].length > 1 && d[0][0] === c && (l = d[0][1]), s.codecs.forEach((u) => {
      if (u.name.toUpperCase() === "RTX" && u.parameters.apt) {
        let f = {
          ssrc: c,
          codecPayloadType: parseInt(u.parameters.apt, 10)
        };
        c && l && (f.rtx = { ssrc: l }), i.push(f), n && (f = JSON.parse(JSON.stringify(f)), f.fec = {
          ssrc: c,
          mechanism: a ? "red+ulpfec" : "red"
        }, i.push(f));
      }
    }), i.length === 0 && c && i.push({
      ssrc: c
    });
    let h = e.matchPrefix(t, "b=");
    return h.length && (h[0].indexOf("b=TIAS:") === 0 ? h = parseInt(h[0].substring(7), 10) : h[0].indexOf("b=AS:") === 0 ? h = parseInt(h[0].substring(5), 10) * 1e3 * 0.95 - 50 * 40 * 8 : h = void 0, i.forEach((u) => {
      u.maxBitrate = h;
    })), i;
  }, e.parseRtcpParameters = function(t) {
    const i = {}, s = e.matchPrefix(t, "a=ssrc:").map((o) => e.parseSsrcMedia(o)).filter((o) => o.attribute === "cname")[0];
    s && (i.cname = s.value, i.ssrc = s.ssrc);
    const n = e.matchPrefix(t, "a=rtcp-rsize");
    i.reducedSize = n.length > 0, i.compound = n.length === 0;
    const a = e.matchPrefix(t, "a=rtcp-mux");
    return i.mux = a.length > 0, i;
  }, e.writeRtcpParameters = function(t) {
    let i = "";
    return t.reducedSize && (i += `a=rtcp-rsize\r
`), t.mux && (i += `a=rtcp-mux\r
`), t.ssrc !== void 0 && t.cname && (i += "a=ssrc:" + t.ssrc + " cname:" + t.cname + `\r
`), i;
  }, e.parseMsid = function(t) {
    let i;
    const s = e.matchPrefix(t, "a=msid:");
    if (s.length === 1)
      return i = s[0].substring(7).split(" "), { stream: i[0], track: i[1] };
    const n = e.matchPrefix(t, "a=ssrc:").map((a) => e.parseSsrcMedia(a)).filter((a) => a.attribute === "msid");
    if (n.length > 0)
      return i = n[0].value.split(" "), { stream: i[0], track: i[1] };
  }, e.parseSctpDescription = function(t) {
    const i = e.parseMLine(t), s = e.matchPrefix(t, "a=max-message-size:");
    let n;
    s.length > 0 && (n = parseInt(s[0].substring(19), 10)), isNaN(n) && (n = 65536);
    const a = e.matchPrefix(t, "a=sctp-port:");
    if (a.length > 0)
      return {
        port: parseInt(a[0].substring(12), 10),
        protocol: i.fmt,
        maxMessageSize: n
      };
    const o = e.matchPrefix(t, "a=sctpmap:");
    if (o.length > 0) {
      const c = o[0].substring(10).split(" ");
      return {
        port: parseInt(c[0], 10),
        protocol: c[1],
        maxMessageSize: n
      };
    }
  }, e.writeSctpDescription = function(t, i) {
    let s = [];
    return t.protocol !== "DTLS/SCTP" ? s = [
      "m=" + t.kind + " 9 " + t.protocol + " " + i.protocol + `\r
`,
      `c=IN IP4 0.0.0.0\r
`,
      "a=sctp-port:" + i.port + `\r
`
    ] : s = [
      "m=" + t.kind + " 9 " + t.protocol + " " + i.port + `\r
`,
      `c=IN IP4 0.0.0.0\r
`,
      "a=sctpmap:" + i.port + " " + i.protocol + ` 65535\r
`
    ], i.maxMessageSize !== void 0 && s.push("a=max-message-size:" + i.maxMessageSize + `\r
`), s.join("");
  }, e.generateSessionId = function() {
    return Math.random().toString().substr(2, 22);
  }, e.writeSessionBoilerplate = function(t, i, s) {
    let n;
    const a = i !== void 0 ? i : 2;
    return t ? n = t : n = e.generateSessionId(), `v=0\r
o=` + (s || "thisisadapterortc") + " " + n + " " + a + ` IN IP4 127.0.0.1\r
s=-\r
t=0 0\r
`;
  }, e.getDirection = function(t, i) {
    const s = e.splitLines(t);
    for (let n = 0; n < s.length; n++)
      switch (s[n]) {
        case "a=sendrecv":
        case "a=sendonly":
        case "a=recvonly":
        case "a=inactive":
          return s[n].substring(2);
      }
    return i ? e.getDirection(i) : "sendrecv";
  }, e.getKind = function(t) {
    return e.splitLines(t)[0].split(" ")[0].substring(2);
  }, e.isRejected = function(t) {
    return t.split(" ", 2)[1] === "0";
  }, e.parseMLine = function(t) {
    const s = e.splitLines(t)[0].substring(2).split(" ");
    return {
      kind: s[0],
      port: parseInt(s[1], 10),
      protocol: s[2],
      fmt: s.slice(3).join(" ")
    };
  }, e.parseOLine = function(t) {
    const s = e.matchPrefix(t, "o=")[0].substring(2).split(" ");
    return {
      username: s[0],
      sessionId: s[1],
      sessionVersion: parseInt(s[2], 10),
      netType: s[3],
      addressType: s[4],
      address: s[5]
    };
  }, e.isValidSDP = function(t) {
    if (typeof t != "string" || t.length === 0)
      return !1;
    const i = e.splitLines(t);
    for (let s = 0; s < i.length; s++)
      if (i[s].length < 2 || i[s].charAt(1) !== "=")
        return !1;
    return !0;
  }, r.exports = e;
})(fg);
var pg = fg.exports;
const Sr = /* @__PURE__ */ Fr(pg), ob = /* @__PURE__ */ Oy({
  __proto__: null,
  default: Sr
}, [pg]);
function va(r) {
  if (!r.RTCIceCandidate || r.RTCIceCandidate && "foundation" in r.RTCIceCandidate.prototype)
    return;
  const e = r.RTCIceCandidate;
  r.RTCIceCandidate = function(i) {
    if (typeof i == "object" && i.candidate && i.candidate.indexOf("a=") === 0 && (i = JSON.parse(JSON.stringify(i)), i.candidate = i.candidate.substring(2)), i.candidate && i.candidate.length) {
      const s = new e(i), n = Sr.parseCandidate(i.candidate);
      for (const a in n)
        a in s || Object.defineProperty(
          s,
          a,
          { value: n[a] }
        );
      return s.toJSON = function() {
        return {
          candidate: s.candidate,
          sdpMid: s.sdpMid,
          sdpMLineIndex: s.sdpMLineIndex,
          usernameFragment: s.usernameFragment
        };
      }, s;
    }
    return new e(i);
  }, r.RTCIceCandidate.prototype = e.prototype, zs(r, "icecandidate", (t) => (t.candidate && Object.defineProperty(t, "candidate", {
    value: new r.RTCIceCandidate(t.candidate),
    writable: "false"
  }), t));
}
function pc(r) {
  !r.RTCIceCandidate || r.RTCIceCandidate && "relayProtocol" in r.RTCIceCandidate.prototype || zs(r, "icecandidate", (e) => {
    if (e.candidate) {
      const t = Sr.parseCandidate(e.candidate.candidate);
      t.type === "relay" && (e.candidate.relayProtocol = {
        0: "tls",
        1: "tcp",
        2: "udp"
      }[t.priority >> 24]);
    }
    return e;
  });
}
function Ea(r, e) {
  if (!r.RTCPeerConnection)
    return;
  "sctp" in r.RTCPeerConnection.prototype || Object.defineProperty(r.RTCPeerConnection.prototype, "sctp", {
    get() {
      return typeof this._sctp > "u" ? null : this._sctp;
    }
  });
  const t = function(o) {
    if (!o || !o.sdp)
      return !1;
    const c = Sr.splitSections(o.sdp);
    return c.shift(), c.some((l) => {
      const d = Sr.parseMLine(l);
      return d && d.kind === "application" && d.protocol.indexOf("SCTP") !== -1;
    });
  }, i = function(o) {
    const c = o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
    if (c === null || c.length < 2)
      return -1;
    const l = parseInt(c[1], 10);
    return l !== l ? -1 : l;
  }, s = function(o) {
    let c = 65536;
    return e.browser === "firefox" && (e.version < 57 ? o === -1 ? c = 16384 : c = 2147483637 : e.version < 60 ? c = e.version === 57 ? 65535 : 65536 : c = 2147483637), c;
  }, n = function(o, c) {
    let l = 65536;
    e.browser === "firefox" && e.version === 57 && (l = 65535);
    const d = Sr.matchPrefix(
      o.sdp,
      "a=max-message-size:"
    );
    return d.length > 0 ? l = parseInt(d[0].substring(19), 10) : e.browser === "firefox" && c !== -1 && (l = 2147483637), l;
  }, a = r.RTCPeerConnection.prototype.setRemoteDescription;
  r.RTCPeerConnection.prototype.setRemoteDescription = function() {
    if (this._sctp = null, e.browser === "chrome" && e.version >= 76) {
      const { sdpSemantics: c } = this.getConfiguration();
      c === "plan-b" && Object.defineProperty(this, "sctp", {
        get() {
          return typeof this._sctp > "u" ? null : this._sctp;
        },
        enumerable: !0,
        configurable: !0
      });
    }
    if (t(arguments[0])) {
      const c = i(arguments[0]), l = s(c), d = n(arguments[0], c);
      let h;
      l === 0 && d === 0 ? h = Number.POSITIVE_INFINITY : l === 0 || d === 0 ? h = Math.max(l, d) : h = Math.min(l, d);
      const u = {};
      Object.defineProperty(u, "maxMessageSize", {
        get() {
          return h;
        }
      }), this._sctp = u;
    }
    return a.apply(this, arguments);
  };
}
function Sa(r) {
  if (!(r.RTCPeerConnection && "createDataChannel" in r.RTCPeerConnection.prototype))
    return;
  function e(i, s) {
    const n = i.send;
    i.send = function() {
      const o = arguments[0], c = o.length || o.size || o.byteLength;
      if (i.readyState === "open" && s.sctp && c > s.sctp.maxMessageSize)
        throw new TypeError("Message too large (can send a maximum of " + s.sctp.maxMessageSize + " bytes)");
      return n.apply(i, arguments);
    };
  }
  const t = r.RTCPeerConnection.prototype.createDataChannel;
  r.RTCPeerConnection.prototype.createDataChannel = function() {
    const s = t.apply(this, arguments);
    return e(s, this), s;
  }, zs(r, "datachannel", (i) => (e(i.channel, i.target), i));
}
function mc(r) {
  if (!r.RTCPeerConnection || "connectionState" in r.RTCPeerConnection.prototype)
    return;
  const e = r.RTCPeerConnection.prototype;
  Object.defineProperty(e, "connectionState", {
    get() {
      return {
        completed: "connected",
        checking: "connecting"
      }[this.iceConnectionState] || this.iceConnectionState;
    },
    enumerable: !0,
    configurable: !0
  }), Object.defineProperty(e, "onconnectionstatechange", {
    get() {
      return this._onconnectionstatechange || null;
    },
    set(t) {
      this._onconnectionstatechange && (this.removeEventListener(
        "connectionstatechange",
        this._onconnectionstatechange
      ), delete this._onconnectionstatechange), t && this.addEventListener(
        "connectionstatechange",
        this._onconnectionstatechange = t
      );
    },
    enumerable: !0,
    configurable: !0
  }), ["setLocalDescription", "setRemoteDescription"].forEach((t) => {
    const i = e[t];
    e[t] = function() {
      return this._connectionstatechangepoly || (this._connectionstatechangepoly = (s) => {
        const n = s.target;
        if (n._lastConnectionState !== n.connectionState) {
          n._lastConnectionState = n.connectionState;
          const a = new Event("connectionstatechange", s);
          n.dispatchEvent(a);
        }
        return s;
      }, this.addEventListener(
        "iceconnectionstatechange",
        this._connectionstatechangepoly
      )), i.apply(this, arguments);
    };
  });
}
function gc(r, e) {
  if (!r.RTCPeerConnection || e.browser === "chrome" && e.version >= 71 || e.browser === "safari" && e._safariVersion >= 13.1)
    return;
  const t = r.RTCPeerConnection.prototype.setRemoteDescription;
  r.RTCPeerConnection.prototype.setRemoteDescription = function(s) {
    if (s && s.sdp && s.sdp.indexOf(`
a=extmap-allow-mixed`) !== -1) {
      const n = s.sdp.split(`
`).filter((a) => a.trim() !== "a=extmap-allow-mixed").join(`
`);
      r.RTCSessionDescription && s instanceof r.RTCSessionDescription ? arguments[0] = new r.RTCSessionDescription({
        type: s.type,
        sdp: n
      }) : s.sdp = n;
    }
    return t.apply(this, arguments);
  };
}
function Ta(r, e) {
  if (!(r.RTCPeerConnection && r.RTCPeerConnection.prototype))
    return;
  const t = r.RTCPeerConnection.prototype.addIceCandidate;
  !t || t.length === 0 || (r.RTCPeerConnection.prototype.addIceCandidate = function() {
    return arguments[0] ? (e.browser === "chrome" && e.version < 78 || e.browser === "firefox" && e.version < 68 || e.browser === "safari") && arguments[0] && arguments[0].candidate === "" ? Promise.resolve() : t.apply(this, arguments) : (arguments[1] && arguments[1].apply(null), Promise.resolve());
  });
}
function ba(r, e) {
  if (!(r.RTCPeerConnection && r.RTCPeerConnection.prototype))
    return;
  const t = r.RTCPeerConnection.prototype.setLocalDescription;
  !t || t.length === 0 || (r.RTCPeerConnection.prototype.setLocalDescription = function() {
    let s = arguments[0] || {};
    if (typeof s != "object" || s.type && s.sdp)
      return t.apply(this, arguments);
    if (s = { type: s.type, sdp: s.sdp }, !s.type)
      switch (this.signalingState) {
        case "stable":
        case "have-local-offer":
        case "have-remote-pranswer":
          s.type = "offer";
          break;
        default:
          s.type = "answer";
          break;
      }
    return s.sdp || s.type !== "offer" && s.type !== "answer" ? t.apply(this, [s]) : (s.type === "offer" ? this.createOffer : this.createAnswer).apply(this).then((a) => t.apply(this, [a]));
  });
}
const lb = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  removeExtmapAllowMixed: gc,
  shimAddIceCandidateNullOrEmpty: Ta,
  shimConnectionState: mc,
  shimMaxMessageSize: Ea,
  shimParameterlessSetLocalDescription: ba,
  shimRTCIceCandidate: va,
  shimRTCIceCandidateRelayProtocol: pc,
  shimSendThrowTypeError: Sa
}, Symbol.toStringTag, { value: "Module" }));
function cb({ window: r } = {}, e = {
  shimChrome: !0,
  shimFirefox: !0,
  shimSafari: !0
}) {
  const t = N1, i = nb(r), s = {
    browserDetails: i,
    commonShim: lb,
    extractVersion: jr,
    disableLog: sb,
    disableWarnings: rb,
    // Expose sdp as a convenience. For production apps include directly.
    sdp: ob
  };
  switch (i.browser) {
    case "chrome":
      if (!Ku || !uc || !e.shimChrome)
        return t("Chrome shim is not included in this adapter release."), s;
      if (i.version === null)
        return t("Chrome shim can not determine version, not shimming."), s;
      t("adapter.js shimming chrome."), s.browserShim = Ku, Ta(r, i), ba(r), U1(r, i), V1(r), uc(r, i), W1(r), K1(r, i), H1(r), Z1(r), X1(r, i), va(r), pc(r), mc(r), Ea(r, i), Sa(r), gc(r, i);
      break;
    case "firefox":
      if (!Xu || !fc || !e.shimFirefox)
        return t("Firefox shim is not included in this adapter release."), s;
      t("adapter.js shimming firefox."), s.browserShim = Xu, Ta(r, i), ba(r), Y1(r, i), fc(r, i), z1(r), J1(r), j1(r), Q1(r), q1(r), eg(r), tg(r), ig(r), sg(r), va(r), mc(r), Ea(r, i), Sa(r);
      break;
    case "safari":
      if (!Yu || !e.shimSafari)
        return t("Safari shim is not included in this adapter release."), s;
      t("adapter.js shimming safari."), s.browserShim = Yu, Ta(r, i), ba(r), cg(r), hg(r), ag(r), rg(r), ng(r), dg(r), og(r), ug(r), va(r), pc(r), Ea(r, i), Sa(r), gc(r, i);
      break;
    default:
      t("Unsupported browser!");
      break;
  }
  return s;
}
cb({ window: typeof window > "u" ? void 0 : window });
class or {
  // eslint-disable-next-line require-jsdoc
  constructor(e) {
    if (!Object.values(wt).some((t) => t === e))
      throw new TypeError("Invalid source.");
    this.source = e, this.deviceId = void 0;
  }
}
class Aa {
  // eslint-disable-next-line require-jsdoc
  constructor(e) {
    if (!Object.values(gt).some((t) => t === e))
      throw new TypeError("Invalid source.");
    this.source = e, this.deviceId = void 0, this.resolution = void 0, this.frameRate = void 0;
  }
}
class Qr {
  // eslint-disable-next-line require-jsdoc
  constructor(e = !1, t = !1) {
    this.audio = e, this.video = t;
  }
}
function Hn(r) {
  return typeof r.video == "object" && r.video.source === gt.SCREENCAST;
}
class Jr {
  /**
   * @function createMediaStream
   * @static
   * @desc Create a MediaStream with given constraints. If you want to create a MediaStream for screen cast, please make sure both audio and video's source are "screen-cast".
   * @memberof Owt.Base.MediaStreamFactory
   * @return {Promise<MediaStream, Error>} Return a promise that is resolved when stream is successfully created, or rejected if one of the following error happened:
   * - One or more parameters cannot be satisfied.
   * - Specified device is busy.
   * - Cannot obtain necessary permission or operation is canceled by user.
   * - Video source is screen cast, while audio source is not.
   * - Audio source is screen cast, while video source is disabled.
   * @param {Owt.Base.StreamConstraints} constraints
   */
  static createMediaStream(e) {
    if (typeof e != "object" || !e.audio && !e.video)
      return Promise.reject(new TypeError("Invalid constrains"));
    if (!Hn(e) && typeof e.audio == "object" && e.audio.source === wt.SCREENCAST)
      return Promise.reject(
        new TypeError("Cannot share screen without video.")
      );
    if (Hn(e) && !eb() && !Wu())
      return Promise.reject(
        new TypeError("Screen sharing only supports Chrome and Firefox.")
      );
    if (Hn(e) && typeof e.audio == "object" && e.audio.source !== wt.SCREENCAST)
      return Promise.reject(new TypeError(
        "Cannot capture video from screen cast while capture audio from other source."
      ));
    if (!e.audio && !e.video)
      return Promise.reject(new TypeError(
        "At least one of audio and video must be requested."
      ));
    const t = /* @__PURE__ */ Object.create({});
    return typeof e.audio == "object" && e.audio.source === wt.MIC ? (t.audio = /* @__PURE__ */ Object.create({}), tb() ? t.audio.deviceId = e.audio.deviceId : t.audio.deviceId = {
      exact: e.audio.deviceId
    }) : e.audio.source === wt.SCREENCAST ? t.audio = !0 : t.audio = e.audio, typeof e.video == "object" ? (t.video = /* @__PURE__ */ Object.create({}), typeof e.video.frameRate == "number" && (t.video.frameRate = e.video.frameRate), e.video.resolution && e.video.resolution.width && e.video.resolution.height && (e.video.source === gt.SCREENCAST ? (t.video.width = e.video.resolution.width, t.video.height = e.video.resolution.height) : (t.video.width = /* @__PURE__ */ Object.create({}), t.video.width.exact = e.video.resolution.width, t.video.height = /* @__PURE__ */ Object.create({}), t.video.height.exact = e.video.resolution.height)), typeof e.video.deviceId == "string" && (t.video.deviceId = { exact: e.video.deviceId }), Wu() && e.video.source === gt.SCREENCAST && (t.video.mediaSource = "screen")) : t.video = e.video, Hn(e) ? navigator.mediaDevices.getDisplayMedia(t) : navigator.mediaDevices.getUserMedia(t);
  }
}
const db = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AudioSourceInfo: wt,
  AudioTrackConstraints: or,
  MediaStreamFactory: Jr,
  Resolution: B1,
  StreamConstraints: Qr,
  TrackKind: ib,
  VideoSourceInfo: gt,
  VideoTrackConstraints: Aa
}, Symbol.toStringTag, { value: "Module" })), { VideoSourceInfo: lr, AudioSourceInfo: Wi } = db, cr = {
  RECVONLY: "recvonly",
  SENDONLY: "sendonly",
  SENDRECV: "sendrecv"
};
function hb(r, e = "detail") {
  Array.isArray(r) || (r = [r]), r.forEach((t) => {
    "contentHint" in t ? (t.contentHint = e, t.contentHint !== e && console.error(`Invalid video track contentHint: "${e}"`)) : console.error("MediaStreamTrack contentHint attribute not supported");
  });
}
function ub(r, ...e) {
  let t = new AudioContext(), i = t.createMediaStreamSource(r), s = t.createMediaStreamDestination();
  return i.connect(s), e.forEach((n) => {
    n.getAudioTracks().forEach((o, c) => {
      let l = new MediaStream();
      l.addTrack(o), t.createMediaStreamSource(l).connect(s);
    });
  }), s.stream;
}
class wn extends qT {
  constructor(e) {
    var i, s, n;
    super("RTCPusherPlayer"), this.TAG = "[RTCPusherPlayer]";
    let t = {
      /**
       * 使用cms录制功能，将本地stream通过rtc推送到cms
       * videoTracks里有两个track. 一个用来初始化交换sdp.一个在cms开始录制时，通过replaceTrack使rtc重编I帧
       */
      recordMediaStream: null,
      element: null,
      // html video element
      debug: !1,
      // if output debug log
      zlmsdpUrl: "",
      simulcast: !1,
      audio: Wi.MIC,
      video: lr.CAMERA,
      mode: cr.RECVONLY,
      resolution: { w: 0, h: 0 },
      usedatachannel: !1,
      videoId: "",
      audioId: "",
      encodedInsertableStreams: !1,
      rtcClientExtend: void 0
    };
    this.options = Object.assign({}, t, e), this.options.debug && JT(), this.e = {
      onicecandidate: this._onIceCandidate.bind(this),
      ontrack: this._onTrack.bind(this),
      onicecandidateerror: this._onIceCandidateError.bind(this),
      onconnectionstatechange: this._onconnectionstatechange.bind(this),
      ondatachannelopen: this._onDataChannelOpen.bind(this),
      ondatachannelmsg: this._onDataChannelMsg.bind(this),
      ondatachannelerr: this._onDataChannelErr.bind(this),
      ondatachannelclose: this._onDataChannelClose.bind(this)
    }, this._remoteStream = null, this._localStream = null, this._tracks = [], (i = this.options.rtcClientExtend) != null && i.initPeerConnection ? this.pc = (n = (s = this.options.rtcClientExtend) == null ? void 0 : s.initPeerConnection) == null ? void 0 : n.call(s, this.options) : this.pc = new RTCPeerConnection(), this.pc.onicecandidate = this.e.onicecandidate, this.pc.onicecandidateerror = this.e.onicecandidateerror, this.pc.ontrack = this.e.ontrack, this.pc.onconnectionstatechange = this.e.onconnectionstatechange, this.datachannel = null, this.options.usedatachannel && (this.datachannel = this.pc.createDataChannel("binary"), this.datachannel.onclose = this.e.ondatachannelclose, this.datachannel.onerror = this.e.ondatachannelerr, this.datachannel.onmessage = this.e.ondatachannelmsg, this.datachannel.onopen = this.e.ondatachannelopen), e.mode !== cr.RECVONLY && (e.audio || e.video) ? this.start() : this.receive();
  }
  async getSdp(e, t) {
    return typeof e == "function" ? e(t).then((i) => ({
      data: {
        code: i ? 0 : -1,
        sdp: i
      }
    })) : e ? fetch(e, {
      method: "post",
      body: t,
      headers: {
        "Content-Type": "text/plain;charset=utf-8"
      },
      mode: "cors",
      referrerPolicy: "no-referrer-when-downgrade"
    }).then((i) => i.json).then((i) => ({ data: i })) : Promise.reject("get sdp need url");
  }
  receive() {
    var n, a, o, c, l, d;
    let e = null, t = null;
    const i = {
      direction: "recvonly",
      sendEncodings: []
    }, s = {
      direction: "recvonly",
      sendEncodings: []
    };
    this.options.video && (t = this.pc.addTransceiver("video", s), (a = (n = this.options.rtcClientExtend) == null ? void 0 : n.setupReceiverTransform) == null || a.call(n, t)), this.options.audio && (e = this.pc.addTransceiver("audio", i), (c = (o = this.options.rtcClientExtend) == null ? void 0 : o.setupReceiverTransform) == null || c.call(o, e)), !((d = (l = this.options.rtcClientExtend) == null ? void 0 : l.initP2P) != null && d.call(l)) && this.pc.createOffer().then((h) => {
      Kt(this.TAG, "receive offer:", h.sdp), this.pc.setLocalDescription(h).then(() => {
        this.getSdp(this.options.zlmsdpUrl, h.sdp).then((u) => {
          let f = u.data;
          if (f.code != 0) {
            this.dispatch(Ge.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, f);
            return;
          }
          let p = {};
          p.sdp = f.sdp, p.type = "answer", Kt(this.TAG, "answer:", f.sdp), this.pc.setRemoteDescription(p).then(() => {
            Kt(this.TAG, "receive set remote sucess");
          }).catch((m) => {
            bs(this.TAG, m);
          });
        });
      });
    }).catch((h) => {
      bs(this.TAG, h);
    });
  }
  start() {
    let e = !1, t = !1;
    const { video: i, audio: s, resolution: n, mode: a, simulcast: o, recordMediaStream: c, videoId: l, audioId: d } = this.options, h = `error paramter video=${i || ""},audio=${s || ""}`;
    if (i && !Object.values(lr).includes(i) || s && !Object.values(Wi).includes(s))
      return Log.e(this.TAG, h);
    const u = i === lr.SCREENCAST, f = s === Wi.SCREENCAST, p = s === Wi.MIXED;
    if (i) {
      let _ = lr.CAMERA;
      u && (_ = lr.SCREENCAST), e = new Aa(_), typeof e == "object" && l != "" && (e.deviceId = l);
    }
    if (s) {
      let _ = Wi.MIC;
      f && (_ = Wi.SCREENCAST), t = new or(_), typeof t == "object" && d != "" && (t.deviceId = d);
    }
    n.w != 0 && n.h != 0 && typeof e == "object" && (e.resolution = new B1(n.w, n.h));
    const m = [];
    let g, x;
    return c && (e = t = !1), u && (p && (t = new or(Wi.SCREENCAST)), g = Jr.createMediaStream(new Qr(f || p ? t : !1, e)), e = !1), f && (t = !1), p && (t = new or(Wi.MIC)), (t || e) && (x = Jr.createMediaStream(new Qr(t, e))), m.push(g, x, c), m.filter(Boolean).length ? Promise.all(m).then(([_, v, E]) => {
      var M, w;
      const b = this.pc;
      let A = _ || v;
      if (_ && v) {
        A = new MediaStream(), _.getVideoTracks().forEach((G) => A.addTrack(G));
        const H = v.getAudioTracks();
        if (p) {
          const G = ub(v, _);
          A.addTrack(G.getAudioTracks()[0]);
        } else
          H.forEach((G) => A.addTrack(G));
      }
      if (E) {
        A = new MediaStream(), E.getAudioTracks().forEach((H) => A.addTrack(H));
        const [N] = E.getVideoTracks();
        if (N) {
          const H = N.clone();
          hb(H, "detail"), A.addTrack(H);
        }
      }
      this._localStream = A, a === cr.SENDONLY && this._attachElement(A), this.dispatch(Ge.WEBRTC_ON_LOCAL_STREAM, A);
      const C = {
        direction: a,
        sendEncodings: []
      }, I = {
        direction: a,
        sendEncodings: []
      }, L = A.getVideoTracks(), R = A.getAudioTracks();
      o && L.length > 0 && (I.sendEncodings = [
        { rid: "h", active: !0, maxBitrate: 1e6 },
        { rid: "m", active: !0, maxBitrate: 5e5, scaleResolutionDownBy: 2 },
        { rid: "l", active: !0, maxBitrate: 2e5, scaleResolutionDownBy: 4 }
      ]), s && (R.length > 0 ? b.addTransceiver(R[0], C) : (C.direction = cr.RECVONLY, b.addTransceiver("audio", C))), i && (L.length > 0 ? b.addTransceiver(L[0], I) : (I.direction = cr.RECVONLY, b.addTransceiver("video", I)));
      const { rtcClientExtend: D } = this.options;
      D && ((M = D.setupSenderTransform) == null || M.call(D), (w = D == null ? void 0 : D.initP2P) != null && w.call(D)) || this.pc.createOffer().then((N) => {
        Kt(this.TAG, "start offer:", N.sdp), this.pc.setLocalDescription(N).then(() => {
          this.getSdp(this.options.zlmsdpUrl, N.sdp).then((H) => {
            let G = H.data;
            if (G.code != 0) {
              this.dispatch(Ge.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, G);
              return;
            }
            let Z = {};
            Z.sdp = G.sdp, Z.type = "answer", Kt(this.TAG, "answer:", G.sdp), this.pc.setRemoteDescription(Z).then(() => {
              Kt(this.TAG, "start set remote sucess");
            }).catch(($) => {
              bs(this.TAG, $);
            });
          });
        });
      }).catch((N) => {
        bs(this.TAG, N);
      });
    }).catch((_) => {
      this.dispatch(Ge.CAPTURE_STREAM_FAILED), bs(this.TAG, _);
    }) : Log.e(this.TAG, h);
  }
  /**
   * 更换track，触发强制I帧
   * @returns 
   */
  // replaceVideoTrack() {
  //     const { recordMediaStream } = this.options;
  //     const [videoTrack] = recordMediaStream?.getVideoTracks() || [];
  //     Log.d(this.TAG, 'replaceVideoTrack videoTrack', videoTrack);
  //     if (!videoTrack) return;
  //     const senderList = this.pc.getSenders();
  //     const videoSender = senderList.find(sender => sender.track.kind === videoTrack.kind);
  //     if (!videoSender) return;
  //     const videoTrackClone = videoTrack.clone();
  //     // setVideoTrackContentHints(videoTrackClone, 'detail');
  //     videoSender.replaceTrack(videoTrackClone);
  // }
  _onIceCandidate(e) {
    e.candidate && Kt(this.TAG, `Remote ICE candidate: 
 ` + e.candidate.candidate);
  }
  _attachElement(e) {
    const { element: t } = this.options;
    t && (t.srcObject = e, t.load());
  }
  _onTrack(e) {
    this._tracks.push(e.track), this.options.element && e.streams && e.streams.length > 0 ? (this.options.element.srcObject = e.streams[0], this._remoteStream = e.streams[0], this.dispatch(Ge.WEBRTC_ON_REMOTE_STREAMS, this._remoteStream)) : this.pc.getReceivers().length == this._tracks.length ? (Kt(this.TAG, "play remote stream "), this._remoteStream = new MediaStream(this._tracks), this.options.element && (this.options.element.srcObject = this._remoteStream), this.dispatch(Ge.WEBRTC_ON_REMOTE_STREAMS, this._remoteStream)) : bs(this.TAG, "wait stream track finish");
  }
  _onIceCandidateError(e) {
    this.dispatch(Ge.WEBRTC_ICE_CANDIDATE_ERROR, e);
  }
  _onconnectionstatechange(e) {
    this.dispatch(Ge.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.pc.connectionState);
  }
  _onDataChannelOpen(e) {
    Kt(this.TAG, "ondatachannel open:", e), this.dispatch(Ge.WEBRTC_ON_DATA_CHANNEL_OPEN, e);
  }
  _onDataChannelMsg(e) {
    Kt(this.TAG, "ondatachannel msg:", e), this.dispatch(Ge.WEBRTC_ON_DATA_CHANNEL_MSG, e);
  }
  _onDataChannelErr(e) {
    Kt(this.TAG, "ondatachannel err:", e), this.dispatch(Ge.WEBRTC_ON_DATA_CHANNEL_ERR, e);
  }
  _onDataChannelClose(e) {
    Kt(this.TAG, "ondatachannel close:", e), this.dispatch(Ge.WEBRTC_ON_DATA_CHANNEL_CLOSE, e);
  }
  sendMsg(e) {
    this.datachannel != null ? this.datachannel.send(e) : bs(this.TAG, "data channel is null");
  }
  switchVideo(e, t) {
    let i = !1;
    return e ? (i = new Aa(gt.CAMERA), i.deviceId = t) : i = new Aa(gt.SCREENCAST), Jr.createMediaStream(new Qr(
      !1,
      i
    )).then((s) => {
      const n = this.pc.getSenders().find((a) => a.track.kind === "video");
      return n != null && s.getVideoTracks().length > 0 ? (this._localStream.removeTrack(n.track), this._localStream.addTrack(s.getVideoTracks()[0]), this.dispatch(Ge.WEBRTC_ON_LOCAL_STREAM, this._localStream), n.replaceTrack(s.getVideoTracks()[0])) : Promise.reject("video not exist or deviceid not vaild");
    });
  }
  switcAudio(e, t) {
    let i = !1;
    return e ? (i = new or(wt.MIC), i.deviceId = t) : i = new or(wt.SCREENCAST), Jr.createMediaStream(new Qr(
      i,
      !1
    )).then((s) => {
      const n = this.pc.getSenders().find((a) => a.track.kind === "audio");
      return n != null && s.getAudioTracks().length > 0 ? (this._localStream.removeTrack(n.track), this._localStream.addTrack(s.getAudioTracks()[0]), this.dispatch(Ge.WEBRTC_ON_LOCAL_STREAM, this._localStream), n.replaceTrack(s.getAudioTracks()[0])) : Promise.reject("audio not exist or deviceid not vaild");
    });
  }
  closeDataChannel() {
    this.datachannel && (this.datachannel.close(), this.datachannel = null);
  }
  close() {
    var e, t;
    (t = (e = this.options.rtcClientExtend) == null ? void 0 : e.close) == null || t.call(e), this.closeDataChannel(), this.pc && (this.pc.close(), this.pc = null), this.options && (this.options = null), this._localStream && this._localStream.getTracks().forEach((i, s) => {
      i.stop();
    }), this._remoteStream && this._remoteStream.getTracks().forEach((i, s) => {
      i.stop();
    }), this._tracks.forEach((i, s) => {
      i.stop();
    }), this._tracks = [];
  }
  get remoteStream() {
    return this._remoteStream;
  }
  get localStream() {
    return this._localStream;
  }
}
wn.AudioSourceInfo = Wi;
wn.VideoSourceInfo = lr;
wn.RTCMode = cr;
var Ed = /* @__PURE__ */ ((r) => (r.RECVONLY = "recvonly", r.SENDONLY = "sendonly", r.SENDRECV = "sendrecv", r))(Ed || {}), mg = /* @__PURE__ */ ((r) => (r.OFFER = "1", r.ANSWER = "2", r))(mg || {}), yt = /* @__PURE__ */ ((r) => (r[r.NONE = 0] = "NONE", r[r.CMS = 1] = "CMS", r[r.P2P = 2] = "P2P", r))(yt || {}), _t = /* @__PURE__ */ ((r) => (r.new = "new", r.connecting = "connecting", r.connected = "connected", r.disconnected = "disconnected", r.failed = "failed", r.closed = "closed", r))(_t || {});
function Qi() {
  let r;
  return self.performance && self.performance.now ? r = self.performance.now.bind(self.performance) : r = Date.now, r();
}
const _c = 500, Zt = _c * 2;
function e0(r, e) {
  return e.some((t) => {
    const i = r.toUpperCase(), s = t.toUpperCase();
    return i.includes(s) || s.includes(i);
  });
}
function gg(r, e, t) {
  if (!(e != null && e.length) && !(t != null && t.length)) return r;
  const i = r.split(/\r|\n/g).filter(Boolean);
  let s = "";
  const n = {}, a = {};
  let o = -1, c = -1;
  const l = e0("H264", e);
  let d;
  l && (d = i.filter((h) => h.startsWith("a=fmtp:") && h.includes("packetization-mode=1")).map((h) => h.split(/:| /g)[1]));
  for (let h = 0; h < i.length; ) {
    const u = i[h];
    if (u.startsWith("m=") && (s = u.split(" ")[0].substring(2), s === "video" ? o = h : s === "audio" && (c = h), !(s === "video" && (e == null ? void 0 : e.length) || s === "audio" && (t == null ? void 0 : t.length)))) {
      for (; !(i[h + 1] && i[h + 1].startsWith("m=")) && (i.splice(h, 1), !(h >= i.length)); )
        ;
      continue;
    }
    if (s === "video" && (e != null && e.length))
      if (u.startsWith("a=rtpmap:")) {
        const f = u.split(" ")[0].split(":")[1].trim(), p = u.split(" ")[1].split("/")[0].trim();
        if (!e0(p, e) || (d == null ? void 0 : d.includes(f)) === !1) {
          i.splice(h, 1);
          continue;
        }
        n[f] = p;
      } else if (u.startsWith("a=rtcp-fb:") || u.startsWith("a=fmtp:")) {
        const f = u.split(" ")[0].split(":")[1];
        if (!n[f]) {
          i.splice(h, 1);
          continue;
        }
      } else u.startsWith("a=extmap:");
    if (s === "audio" && (t != null && t.length)) {
      if (u.startsWith("a=rtpmap:")) {
        const f = u.split(" ")[0].split(":")[1].trim(), p = u.split(" ")[1].trim();
        if (!e0(p, t)) {
          i.splice(h, 1);
          continue;
        }
        a[f] = p;
      } else if (u.startsWith("a=rtcp-fb:") || u.startsWith("a=fmtp:")) {
        const f = u.split(" ")[0].split(":")[1];
        if (!a[f]) {
          i.splice(h, 1);
          continue;
        }
      }
    }
    h++;
  }
  return ["video", "audio"].forEach((h) => {
    const u = h === "video" ? o : c, f = h === "video" ? n : a;
    if (u < 0 || u >= i.length) return;
    const m = i[u].split(" "), g = m.splice(3, m.length - 3);
    m.push.apply(
      m,
      g.filter((x) => !!f[x])
    ), i[u] = m.join(" ");
  }), i.join(`\r
`) + `\r
`;
}
const zu = `${Bt.CMD_THING_INVOKE_SERVICE}.${rt.P2PSignalCandidate}`, ju = `${Bt.CMD_THING_INVOKE_SERVICE}.${rt.P2PSignalSdp}`, Zn = "P2PSignalingProxy", un = class un extends ve {
  /**
   *
   * @param {*} signalingWebSocket 信令终端
   * @param {*} playerDeviceInfo 播放设备信息
   */
  constructor(t, i) {
    var d, h;
    super();
    y(this, "signalingWebSocket", null);
    y(this, "productKey");
    y(this, "deviceName");
    y(this, "lensId");
    y(this, "streamChannelId");
    y(this, "streamName");
    y(this, "onP2PSignalSdpCallback", null);
    y(this, "onP2PSignalCandidateCallback", null);
    y(this, "playerDeviceInfo");
    y(this, "isSdCardReuse", !1);
    const { productKey: s, deviceName: n, lensId: a = 0, streamChannelId: o, seekParam: c } = i;
    this.playerDeviceInfo = i, this.signalingWebSocket = t, this.productKey = s, this.deviceName = n, this.lensId = a, this.streamChannelId = o;
    const l = c != null && c.isSDCard ? "sdcardplayback" : "live";
    this.streamName = `${n}_${o}_l${a}_${l}_${Date.now()}_chan_P2P`, this.onP2PSignalSdpCallback = (u) => {
      const p = u.params.Sdp;
      p && this.emit(un.ProxyEvents.P2PSignalSdp, p);
    }, (d = this.signalingWebSocket) == null || d.on(ju, this.onP2PSignalSdpCallback), this.onP2PSignalCandidateCallback = (u) => {
      var m;
      const p = u.params.Candidate;
      p && ((m = this.emit) == null || m.call(this, un.ProxyEvents.P2PSignalCandidate, p));
    }, (h = this.signalingWebSocket) == null || h.on(zu, this.onP2PSignalCandidateCallback);
  }
  startP2PStream() {
    var s;
    S.d(Zn, "startP2PStream");
    const t = this.isSdCardReuse ? "1" : "0", i = {
      productKey: this.productKey,
      deviceName: this.deviceName,
      lensId: this.lensId,
      identifier: rt.StartP2PStreaming,
      params: {
        App: this.productKey,
        Stream: this.streamName,
        Channel: this.streamChannelId + "",
        Scheme: Ga.RTC,
        ConnectMode: t
      },
      ack: Ke.NEED_ACK
    };
    return (s = this.signalingWebSocket) == null ? void 0 : s.invokeThingService(i);
  }
  destroy() {
    var t, i;
    this.signalingWebSocket && (S.d(Zn, "destroy"), this.onP2PSignalSdpCallback && ((t = this.signalingWebSocket) == null || t.off(ju, this.onP2PSignalSdpCallback)), this.onP2PSignalCandidateCallback && ((i = this.signalingWebSocket) == null || i.off(zu, this.onP2PSignalCandidateCallback)), this.signalingWebSocket = null, this.onP2PSignalSdpCallback = null, this.onP2PSignalCandidateCallback = null);
  }
  sendP2PSdpToRemotePeer(t) {
    var s;
    S.d(Zn, "sendP2PSdpToRemotePeer", !!this.signalingWebSocket);
    const i = {
      productKey: this.productKey,
      deviceName: this.deviceName,
      lensId: this.lensId,
      identifier: rt.P2PSignalSdp,
      params: {
        Type: mg.OFFER,
        // 1 offer 2 answer
        Sdp: t,
        Channel: this.streamChannelId + "",
        Stream: this.streamName
      },
      ack: Ke.NEED_ACK
    };
    (s = this.signalingWebSocket) == null || s.invokeThingService(i).then(() => this.startP2PStream());
  }
  sendCandidateToRemotePeer(t) {
    var s;
    S.d(Zn, "sendCandidateToRemotePeer", !!this.signalingWebSocket);
    const i = {
      productKey: this.productKey,
      deviceName: this.deviceName,
      lensId: this.lensId,
      identifier: rt.P2PSignalCandidate,
      params: {
        Candidate: t,
        Stream: this.streamName
      },
      ack: Ke.NO_ACK
    };
    (s = this.signalingWebSocket) == null || s.invokeThingService(i);
  }
  /**
   * p2p裁剪sdp供设备使用
   * @param sdp 协商描述
   * @param videoCodecs 指定视频编码
   * @param audioCodecs 指定音频编码
   * @returns
   */
  simplifySdp(t) {
    const { videoCodec: i, audioCodec: s } = this.playerDeviceInfo;
    return gg(t, i ? [i] : [], s ? [s] : []);
  }
};
y(un, "ProxyEvents", {
  P2PSignalCandidate: "P2PSignalCandidate",
  P2PSignalSdp: "P2PSignalSdp"
});
let gn = un;
const gi = "RTCClientExtend";
class fb {
  constructor(e, t) {
    y(this, "pc", null);
    y(this, "p2pSignalingProxy");
    y(this, "endpointOption");
    y(this, "stunServer");
    y(this, "receivedRemoteCandidate", []);
    y(this, "onP2PSignalCandidate", (e) => {
      var i, s;
      if (!((i = this.pc) != null && i.remoteDescription)) {
        this.receivedRemoteCandidate.push(e);
        return;
      }
      let t = {
        sdpMid: "0",
        sdpMLineIndex: 0,
        candidate: e
      };
      S.d(gi, "candidate:", t), (s = this.pc) == null || s.addIceCandidate(t).then(() => {
        S.d(gi, "add candidate sucess");
      }).catch((n) => {
        S.e(gi, n);
      });
    });
    y(this, "onP2PSignalSdp", (e) => {
      var s;
      const t = ["http://www.rtcrtc.com/data_record", "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"];
      if (e = e.split(/\n|\r/g).filter((n) => n && !t.some((a) => n.includes(a))).join(`\r
`) + `\r
`, S.k(gi, "onP2PSignalSdp remoteSdp=" + e), !e) {
        S.e(gi, "onP2PSignalSdp remoteSdp error");
        return;
      }
      let i = {
        sdp: e,
        type: "answer"
      };
      (s = this.pc) == null || s.setRemoteDescription(i).then(() => {
        S.d(gi, "set remote sucess"), this.receivedRemoteCandidate.length && (this.receivedRemoteCandidate.forEach(this.onP2PSignalCandidate), this.receivedRemoteCandidate = []);
      }).catch((n) => {
        S.e(gi, n);
      });
    });
    y(this, "startNegotiationneed", () => {
      var e;
      (e = this.pc) == null || e.createOffer().then((t) => {
        var i;
        S.d(gi, "startNegotiationneed offer:", t.sdp), (i = this.pc) == null || i.setLocalDescription(t).then(() => {
          var n, a;
          const s = (a = (n = this.p2pSignalingProxy) == null ? void 0 : n.simplifySdp) == null ? void 0 : a.call(n, t.sdp ?? "");
          S.k(gi, "startNegotiationneed offer new :", s), s && this.sendP2PSdpToRemotePeer(s);
        });
      });
    });
    y(this, "videoReceiveController");
    y(this, "audioReceiveController");
    y(this, "videoSendController");
    y(this, "audioSendController");
    y(this, "setupSenderTransformSingle", (e) => {
      const { encodedInsertableStreams: t, mediaEncodeCallback: i } = this.endpointOption || {};
      if (!t || !(e != null && e.createEncodedStreams) || !i) return;
      const s = e.createEncodedStreams(), n = s.readableStream || s.readable, a = s.writableStream || s.writable, o = new TransformStream({
        transform: (c, l) => {
          const d = e.track.kind;
          d === "video" ? this.videoSendController || (this.videoSendController = l) : d === "audio" && (this.audioSendController || (this.audioSendController = l)), setTimeout(() => i(c, l, e), 0);
        }
      });
      n.pipeThrough(o).pipeTo(a);
    });
    this.p2pSignalingProxy = e, this.stunServer = t;
  }
  initPeerConnection(e) {
    this.endpointOption = e;
    const t = {
      iceTransportPolicy: "all",
      bundlePolicy: "max-bundle",
      encodedInsertableStreams: !!(e.encodedInsertableStreams && (e.mediaEncodeCallback || e.mediaDecodeCallback))
    };
    return this.stunServer && (t.iceServers = [
      // { urls: "stun:stun.l.google.com:19302"}
      { urls: this.stunServer }
    ]), this.pc = new RTCPeerConnection(t), setTimeout(this.startNegotiationneed), this.pc;
  }
  initP2P() {
    const e = this.p2pSignalingProxy;
    return e ? (e.on(gn.ProxyEvents.P2PSignalCandidate, this.onP2PSignalCandidate), e.on(gn.ProxyEvents.P2PSignalSdp, this.onP2PSignalSdp), !0) : !1;
  }
  close() {
    var e, t;
    (t = (e = this.p2pSignalingProxy) == null ? void 0 : e.destroy) == null || t.call(e);
  }
  sendP2PSdpToRemotePeer(e) {
    var i;
    const t = this.p2pSignalingProxy;
    return S.d(gi, "startP2P sendP2PSdpToRemotePeer", !!t), t ? ((i = t.sendP2PSdpToRemotePeer) == null || i.call(t, e), !0) : !1;
  }
  setupReceiverTransform(e) {
    const { receiver: t } = e, { encodedInsertableStreams: i, mediaDecodeCallback: s } = this.endpointOption || {};
    if (!i || !(t != null && t.createEncodedStreams) || !s) return;
    const n = t.createEncodedStreams(), a = n.readableStream || n.readable, o = n.writableStream || n.writable, c = new self.TransformStream({
      transform: (l, d) => {
        const h = t.track.kind;
        h === "video" ? this.videoReceiveController || (this.videoReceiveController = d) : h === "audio" && (this.audioReceiveController || (this.audioReceiveController = d)), setTimeout(() => s(l, d, t), 0);
      }
    });
    a.pipeThrough(c).pipeTo(o);
  }
  setupSenderTransform() {
    var e;
    (e = this.pc) == null || e.getSenders().forEach(this.setupSenderTransformSingle);
  }
}
class on extends ve {
  constructor(t) {
    super();
    y(this, "TAG");
    y(this, "options");
    y(this, "endpoint");
    y(this, "mediaElementLinsters");
    y(this, "playAbsTimestamp");
    y(this, "dataChannelParentCount", 0);
    y(this, "dataChannelOpened", !1);
    y(this, "connectStatus", _t.new);
    y(this, "videoQueue", []);
    y(this, "lastVideoTime", 0);
    y(this, "videoInterval");
    y(this, "videoBaseTimestamp", -1);
    y(this, "audioBaseTimestamp", -1);
    y(this, "lastAudioTimestamp", -1);
    y(this, "lastVideoTimestamp", -1);
    /**
     * 修复硬解首屏黑屏问题
     * @param {*} chunk
     * @param {*} controller
     * @param {*} receiver
     * @returns
     */
    y(this, "mediaDecodeCallback", async (t, i, s) => {
      if (!this.endpoint) return;
      const { mediaDecodeCallback: n } = this.options;
      if (s.track.kind === "video") {
        this.videoBaseTimestamp < 0 && (this.videoBaseTimestamp = t.timestamp);
        const l = (this.lastVideoTimestamp < 0 ? 0 : t.timestamp - this.lastVideoTimestamp) / 90, d = `rtc video ${t.type} time ` + (t.timestamp - this.videoBaseTimestamp) / 90 + " delta=" + l;
        l >= 0 || S.e(this.TAG, d), this.lastVideoTimestamp = t.timestamp;
      } else {
        this.audioBaseTimestamp < 0 && (this.audioBaseTimestamp = t.timestamp);
        const l = (this.lastAudioTimestamp < 0 ? 0 : t.timestamp - this.lastAudioTimestamp) / 8, d = "rtc audio time " + (t.timestamp - this.audioBaseTimestamp) / 8 + " delta=" + l;
        l >= 0 || S.e(this.TAG, d), this.lastAudioTimestamp = t.timestamp, n && (t = n(t)), i.enqueue(t);
        return;
      }
      const c = Qi();
      if (!this.lastVideoTime || c - this.lastVideoTime >= 10 && !this.videoInterval) {
        this.lastVideoTime = c, this.updateLiveTime(t), n && (t = n(t)), i.enqueue(t);
        return;
      }
      this.videoQueue.push({ chunk: t, controller: i, receiver: s }), !this.videoInterval && (this.videoInterval = setInterval(() => {
        const l = this.videoQueue.shift();
        if (!l) {
          clearInterval(this.videoInterval), this.videoInterval = void 0;
          return;
        }
        const { chunk: d, controller: h } = l;
        this.lastVideoTime = Qi(), this.updateLiveTime(d), h.enqueue(d);
      }, 10));
    });
    y(this, "onvCanPlay", () => this.emit("canplay"));
    y(this, "onvEnded", () => this.emit("ended"));
    y(this, "onvError", () => this.emit("error"));
    y(this, "onvPlaying", () => this.emit("playing"));
    y(this, "onvTimeupdate", () => {
      this.onvPlaying(), this.emit("timeupdate", this.mediaElement.currentTime * 1e3);
    });
    this.TAG = S.traceTag("RTCPlayer", t.traceId), this.options = t, this.mediaElementLinsters = {
      canplay: this.onvCanPlay,
      ended: this.onvEnded,
      error: this.onvError,
      playing: this.onvPlaying,
      timeupdate: this.onvTimeupdate
    }, (!t.usedatachannel || t.channelMode == yt.P2P) && this.init();
  }
  get deviceInfo() {
    return this.options.deviceInfo;
  }
  get channelMode() {
    return this.options.channelMode;
  }
  get mediaElement() {
    return this.options.element;
  }
  get absTimestamp() {
    return this.playAbsTimestamp;
  }
  sendDataChannelMessage(t) {
    var i;
    (i = this.endpoint) == null || i.sendMsg(t);
  }
  destroy() {
    var i, s;
    clearInterval(this.videoInterval), this.videoQueue = [], (i = this.endpoint) == null || i.offAll(), (s = this.endpoint) == null || s.close(), this.endpoint = void 0;
    const { element: t } = this.options;
    t && typeof t != "function" && Object.entries(this.mediaElementLinsters).forEach(([n, a]) => {
      t.removeEventListener(n, a);
    }), this == null || this.removeAllListeners();
  }
  init() {
    let t;
    const { p2pSignalingProxy: i } = this.options;
    t = new fb(i, this.options.stunServer);
    const { usedatachannel: s = !1, element: n, zlmsdpUrl: a, video: o = !0, audio: c = !0, debug: l, encodedInsertableStreams: d } = this.options, h = {
      element: n,
      // video/audio 标签
      debug: l,
      // 是否打印日志
      zlmsdpUrl: a,
      // 流地址
      simulcast: !1,
      video: o,
      audio: c && !!this.deviceInfo.audioCodec,
      mode: Ed.RECVONLY,
      usedatachannel: s,
      encodedInsertableStreams: d,
      mediaDecodeCallback: this.mediaDecodeCallback,
      rtcClientExtend: t
    }, u = this.endpoint = new wn(h);
    this.initListener(u);
  }
  initListener(t) {
    const {
      WEBRTC_ICE_CANDIDATE_ERROR: i,
      WEBRTC_ON_REMOTE_STREAMS: s,
      WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: n,
      WEBRTC_ON_LOCAL_STREAM: a,
      CAPTURE_STREAM_FAILED: o,
      WEBRTC_ON_CONNECTION_STATE_CHANGE: c,
      WEBRTC_ON_DATA_CHANNEL_OPEN: l,
      WEBRTC_ON_DATA_CHANNEL_MSG: d,
      WEBRTC_ON_DATA_CHANNEL_CLOSE: h,
      WEBRTC_ON_DATA_CHANNEL_ERR: u
    } = Ge;
    t.on(c, (p) => {
      this.connectStatus = p, p != _t.connected && (this.dataChannelOpened = !1), this.emit(c, p);
    }), t.on(i, (p) => {
      this.emit(i, p), S.e(this.TAG, i, p);
    }), t.on(s, (p) => {
      this.emit(s, p);
    }), t.on(n, (p) => {
      S.e(this.TAG, n, p), this.emit(n, p), this.destroy();
    }), t.on(a, (p) => {
      this.emit(a, p);
    }), t.on(o, (p) => {
      S.d(this.TAG, o), this.emit(o, p);
    }), t.on(l, (p) => {
      S.d(this.TAG, l), this.dataChannelOpened = !0, this.emit(l, p);
    }), t.on(d, (p) => {
      this.emit(d, p);
    }), t.on(h, (p) => {
      S.d(this.TAG, h), this.dataChannelOpened = !1, this.emit(h, p);
    }), t.on(u, (p) => {
      S.d(this.TAG, u), this.dataChannelOpened = !1, this.emit(u, p);
    });
    const { element: f } = this.options;
    f && typeof f != "function" && Object.entries(this.mediaElementLinsters).forEach(([p, m]) => {
      f.addEventListener(p, m);
    });
  }
  updateLiveTime(t) {
    let { absTimestamp: i } = t;
    i && (this.playAbsTimestamp = i);
  }
}
y(on, "Events", Ge);
var yc = /* @__PURE__ */ ((r) => (r.CMS = "CMS", r.P2P = "P2P", r))(yc || {}), jt = /* @__PURE__ */ ((r) => (r.Video = "video", r.Audio = "audio", r))(jt || {}), Sd = /* @__PURE__ */ ((r) => (r.WCSVideoRender = "WCSVideoRender", r.WCSCanvasRender = "WCSCanvasRender", r))(Sd || {}), Td = /* @__PURE__ */ ((r) => (r.PCMRender = "PCMRender", r))(Td || {}), Ns = /* @__PURE__ */ ((r) => (r[r.LIVE = 0] = "LIVE", r[r.SDCARD = 1] = "SDCARD", r[r.PUSH = 2] = "PUSH", r))(Ns || {});
class Ao extends ve {
  /**
   *
   * @param {*} signalingWebSocket 信令终端
   * @param {*} playerDeviceInfo 播放设备信息
   */
  constructor(t, i, s) {
    super();
    y(this, "TAG", "SignalingProxy");
    y(this, "streamName");
    y(this, "signalingWebSocket");
    y(this, "playerDeviceInfo");
    y(this, "isSdCardReuse", !1);
    y(this, "isP2PChannel", !1);
    y(this, "signalingProxyType");
    this.signalingWebSocket = t, this.playerDeviceInfo = i, this.signalingProxyType = s;
    const { deviceName: n, lensId: a = 0, streamChannelId: o, seekParam: c } = this.playerDeviceInfo, l = `${n}_${a}`, d = Date.now();
    this.streamName = s == 1 ? `${l}_sdcard_${(c == null ? void 0 : c.beginTime) ?? d}` : s === 2 ? `${l}_push_${Rn()}` : `${l}_${o}`;
  }
  async exchangeSdp(t, i, s = Na.RTC) {
    var m, g;
    const { productKey: n, deviceName: a, streamChannelId: o, seekParam: c } = this.playerDeviceInfo, l = c == null ? void 0 : c.isSDCard, d = this.signalingProxyType === 2, h = l ? void 0 : o.toString(), u = {
      type: l ? ha.DEV_PLAY : d ? ha.Push : ha.PLAY,
      protocol: s,
      productKey: n,
      deviceName: a,
      sdp: t,
      stream: i || this.streamName,
      channel: h
    }, f = await this.signalingWebSocket.thingMediaGet(u), p = ((m = f == null ? void 0 : f.data) == null ? void 0 : m.sdp) || ((g = f == null ? void 0 : f.data) == null ? void 0 : g.url);
    return S.k(this.TAG, "exchangeSdp remoteSdp=" + p), p;
  }
  async seekSdCard(t, i) {
    const s = this.isP2PChannel || this.isSdCardReuse && i == yt.CMS ? "1" : "0", n = this.isSdCardReuse ? "1" : "0";
    t.seekType === xd.TYPE_SDCARD_FILE ? this.seekSdcardByFile(t, i, s, n) : this.seekSdcardByTime(t, i, s, n);
  }
  stopCmsLivePreview() {
    var a;
    const { productKey: t, deviceName: i, lensId: s = 0 } = this.playerDeviceInfo, n = {
      productKey: t,
      deviceName: i,
      lensId: s,
      identifier: rt.StopCmsLivePreview,
      params: {
        stream: this.streamName
      },
      ack: Ke.NO_ACK
    };
    (a = this.signalingWebSocket) == null || a.invokeThingService(n);
  }
  stopVod() {
    var a;
    const { productKey: t, deviceName: i, lensId: s = 0 } = this.playerDeviceInfo, n = {
      productKey: t,
      deviceName: i,
      lensId: s,
      identifier: rt.StopVod,
      params: {
        App: t,
        Stream: this.streamName
      },
      ack: Ke.NO_ACK
    };
    (a = this.signalingWebSocket) == null || a.invokeThingService(n);
  }
  /**
   * 通知设备开始拉流
   */
  notifyDeviceStartPullStream() {
    var a;
    const { productKey: t, deviceName: i, lensId: s = 0 } = this.playerDeviceInfo, n = {
      productKey: t,
      deviceName: i,
      lensId: s,
      identifier: rt.StartVoiceIntercom,
      params: {
        App: t,
        Stream: this.streamName,
        Protocol: Na.RTC
      },
      ack: Ke.NEED_ACK
    };
    return (a = this.signalingWebSocket) == null ? void 0 : a.invokeThingService(n);
  }
  /**
   * 通知设备结束拉流
   */
  notifyDeviceStopPullStream() {
    var a;
    const { productKey: t, deviceName: i, lensId: s = 0 } = this.playerDeviceInfo, n = {
      productKey: t,
      deviceName: i,
      lensId: s,
      identifier: rt.StopVoiceIntercom,
      params: {
        App: t,
        Stream: this.streamName
      },
      ack: Ke.NO_ACK
    };
    (a = this.signalingWebSocket) == null || a.invokeThingService(n);
  }
  /**
   * 通知设备创建DataChannel
   */
  notifyDeviceCreateChannel(t) {
    var o;
    const { productKey: i, deviceName: s, lensId: n = 0 } = this.playerDeviceInfo, a = {
      productKey: i,
      deviceName: s,
      lensId: n,
      identifier: rt.CreateDataChannel,
      params: {
        App: i,
        Stream: t,
        ChannelName: "binary"
      },
      ack: Ke.NO_ACK
    };
    (o = this.signalingWebSocket) == null || o.invokeThingService(a);
  }
  /**
   * 通知设备销毁DataChannel
   */
  notifyDeviceDestroyChannel(t) {
    var o;
    const { productKey: i, deviceName: s, lensId: n = 0 } = this.playerDeviceInfo, a = {
      productKey: i,
      deviceName: s,
      lensId: n,
      identifier: rt.DestroyDataChannel,
      params: {
        App: i,
        Stream: t
      },
      ack: Ke.NO_ACK
    };
    (o = this.signalingWebSocket) == null || o.invokeThingService(a);
  }
  seekSdcardByFile(t, i, s, n) {
    const { productKey: a, deviceName: o, lensId: c = 0 } = this.playerDeviceInfo, l = {
      productKey: a,
      deviceName: o,
      lensId: c,
      identifier: rt.StartVod,
      params: {
        App: a,
        Stream: this.streamName,
        Scheme: Ga.RTC,
        PushUrl: "",
        SeekTime: ((t == null ? void 0 : t.seekPos) ?? 0).toString(),
        FileName: t.filename,
        Mode: i,
        Action: n,
        ConnectMode: s
      },
      ack: Ke.NEED_ACK
    };
    this.signalingWebSocket.invokeThingService(l);
  }
  seekSdcardByTime(t, i, s, n) {
    var u;
    const { productKey: a, deviceName: o, lensId: c = 0 } = this.playerDeviceInfo;
    let { beginTime: l, endTime: d } = t;
    d = d ?? l + 5 * 6e5;
    const h = {
      productKey: a,
      deviceName: o,
      lensId: c,
      identifier: rt.StartVodByTime,
      params: {
        App: a,
        Stream: this.streamName,
        Scheme: Ga.RTC,
        PushUrl: "",
        BeginTime: l.toString(),
        EndTime: d.toString(),
        Mode: i.toString(),
        Action: n,
        ConnectMode: s
      },
      ack: Ke.NEED_ACK
    };
    (u = this.signalingWebSocket) == null || u.invokeThingService(h);
  }
}
const pb = {
  mp3: ae.MP3,
  opus: ae.OPUS,
  vorbis: ae.OPUS,
  ulaw: ae.PCMU,
  alaw: ae.PCMA
};
function _g(r) {
  switch (r) {
    case de.H264:
      return "avc1.42001f";
    case de.H265:
      return "hev1.1.2.L120.80";
    default:
      return "";
  }
}
function Ca(r) {
  switch (r) {
    case ae.PCMA:
      return "alaw";
    case ae.PCMU:
      return "ulaw";
    case ae.AAC:
      return "mp4a.40.2";
    case ae.OPUS:
      return "opus";
    default:
      return "";
  }
}
function xc(r) {
  return r ? (r = r.toLowerCase(), r.startsWith("avc") ? de.H264 : r.startsWith("hev1") || r.startsWith("hvc1") ? de.H265 : r.startsWith("vp8") ? de.VP8 : r.startsWith("vp09") ? de.VP9 : r.startsWith("vp10") ? de.VP10 : r.startsWith("av01") ? de.AV1 : r) : de.NONE;
}
function za(r) {
  return r ? (r = r.toLowerCase(), (r.startsWith("mp4a") ? ae.AAC : r.startsWith("pcm-") ? ae.PCM : pb[r]) ?? ae.NONE) : ae.NONE;
}
function mb(r) {
  return r ? (r = r.toLowerCase().split(",")[0], r == "h264" ? de.H264 : r == "h265" ? de.H265 : r == "vp8" ? de.VP8 : r == "vp9" ? de.VP9 : r == "vp10" ? de.VP10 : r == "av1" ? de.AV1 : de.NONE) : de.NONE;
}
function gb(r) {
  return r ? (r = r.toLowerCase(), (r.startsWith("mpeg4-generic") || r === "aac" ? ae.AAC : r.startsWith("opus/48000") || r === "opus" ? ae.OPUS : r.startsWith("pcma/8000") || r === "pcma" ? ae.PCMA : r.startsWith("pcmu/8000") || r === "pcmu" ? ae.PCMU : ae.NONE) ?? ae.NONE) : ae.NONE;
}
class $n {
  constructor(e, t, i, s) {
    y(this, "type", "WebRTCPlayer");
    y(this, "TAG");
    y(this, "videoMeta", null);
    // private playerWrapper: Element | null = null;
    y(this, "mediaElement", null);
    y(this, "mediaDataSource");
    y(this, "emitter", new ve());
    y(this, "config");
    y(this, "mediaListeners");
    y(this, "pendingSeekTime");
    y(this, "statisticsReporterInterval");
    y(this, "rtcCMSPlayer");
    y(this, "rtcP2PPlayer");
    y(this, "rtcPlayer");
    // private receivedCanPlay: boolean = false;
    y(this, "fakePlaybackRate", 1);
    y(this, "p2pSignalingProxy");
    y(this, "signalingProxy");
    y(this, "chanelModel", yt.NONE);
    y(this, "p2pInitTimer");
    y(this, "playerDeviceInfo");
    y(this, "playDurationLimitTimer", -1);
    y(this, "doPlayDurationLimit", () => {
      S.w(this.TAG, `doPlayDurationLimit duration=${this.config.playLimitDuration}s`), this.proxyEmit(z.PLAY_ENDED);
    });
    y(this, "onP2pStreamPrepare", () => {
      var t, i;
      S.i(this.TAG, "p2p can play");
      const { mediaElement: e } = this.rtcP2PPlayer || {};
      e && (e.setAttribute("player-type", this.type + "_P2P"), (i = (t = this.mediaElement) == null ? void 0 : t.parentNode) == null || i.replaceChild(e, this.mediaElement), this.mediaElement = e, e.oncanplay = null, this.chanelModel = yt.P2P, this.attachMediaElement(), clearTimeout(this.playDurationLimitTimer), this.destroyCMSPlayer(), this.rtcPlayer = this.rtcP2PPlayer, S.i(this.TAG, "switch to p2p"), this.proxyEmit(z.CHANNEL_CHANGE, this.chanelModel));
    });
    y(this, "watchVideoResolutionChange", () => {
      const { videoWidth: e = 0, videoHeight: t = 0 } = this.mediaElement || {};
      (!this.videoMeta || this.videoMeta.codecWidth !== e) && (this.videoMeta = {
        codec: _g(de.H265),
        codecType: de.H265,
        codecWidth: e,
        codecHeight: t
      });
    });
    y(this, "noDataReceivedTimer");
    if (this.TAG = S.traceTag("WebRTCPlayer", t.traceId), this.playerDeviceInfo = i, s || (s = Ii(t.traceId)), !e.url) {
      !i.seekParam && !t.disableP2P && (this.p2pSignalingProxy = new gn(s, i));
      const n = i != null && i.seekParam ? Ns.SDCARD : Ns.LIVE;
      this.signalingProxy = new Ao(s, i, n);
    }
    this.config = Pr(), typeof t == "object" && Object.assign(this.config, t), this.mediaListeners = {
      loadedMetadata: this.onvLoadedMetadata.bind(this),
      canPlay: this.onvCanPlay.bind(this),
      loadedData: this.onvLoadedData.bind(this),
      ended: this.onvEnded.bind(this),
      error: this.onvError.bind(this),
      playing: this.onvPlaying.bind(this),
      timeupdate: this.onvTimeupdate.bind(this)
    }, this.mediaDataSource = e, this.initMediaElement();
  }
  static async isSupport(e, t) {
    const i = new RTCPeerConnection();
    return i.addTransceiver("video", {
      direction: "recvonly",
      sendEncodings: []
    }), i.addTransceiver("audio", {
      direction: "recvonly",
      sendEncodings: []
    }), i.createOffer().then((s) => {
      var o, c;
      i.close();
      const n = !!((o = s.sdp) != null && o.includes(` ${e}/`)), a = !!((c = s.sdp) != null && c.includes(` ${t}/`));
      return (!n || !a) && S.w("WebRTCPlayer", s.sdp, e, t), [n, a];
    }).catch(() => [!1, !1]);
  }
  seekTo(e) {
    var t;
    this.signalingProxy && (this.signalingProxy.isSdCardReuse = !0), this.p2pSignalingProxy && (this.p2pSignalingProxy.isSdCardReuse = !0), this.chanelModel !== yt.NONE && ((t = this.signalingProxy) == null || t.seekSdCard(e, this.chanelModel));
  }
  destroy() {
    var e, t, i;
    clearTimeout(this.playDurationLimitTimer), (e = this.playerDeviceInfo.seekParam) != null && e.isSDCard && ((t = this.signalingProxy) == null || t.stopVod()), this.stopWatchNoDataReceived(), this.destroyRTCPlayer(), this.mediaElement && (this.unload(), this.detachMediaElement()), this.mediaListeners = {}, this.mediaDataSource = void 0, (i = this.emitter) == null || i.removeAllListeners(), this.emitter = void 0;
  }
  on(e, t) {
    var s;
    const i = this.mediaElement;
    e === z.MEDIA_INFO ? i != null && i.readyState !== 0 && Promise.resolve().then(() => {
      this.proxyEmit(z.MEDIA_INFO, this.mediaInfo);
    }) : e === z.STATISTICS_INFO && i != null && i.readyState !== 0 && Promise.resolve().then(() => {
      this.proxyEmit(z.STATISTICS_INFO, this.statisticsInfo);
    }), (s = this.emitter) == null || s.addListener(e, t);
  }
  off(e, t) {
    var i;
    (i = this.emitter) == null || i.removeListener(e, t);
  }
  attachMediaElement() {
    const e = this.mediaElement;
    if (e && this.pendingSeekTime != null)
      try {
        e.currentTime = this.pendingSeekTime, this.pendingSeekTime = void 0;
      } catch {
      }
  }
  detachMediaElement() {
    this.clearReportInterval();
  }
  load() {
    var p;
    const e = this.mediaElement;
    if (!e)
      throw new qe("HTMLMediaElement must be attached before load()!");
    const t = async (m) => {
      var _, v, E;
      if (typeof ((_ = this.mediaDataSource) == null ? void 0 : _.url) == "function")
        return await this.mediaDataSource.url(oi.WebRTC, m);
      const { seekParam: g } = this.playerDeviceInfo;
      return g && ((v = this.signalingProxy) == null || v.seekSdCard(g, this.chanelModel)), await ((E = this.signalingProxy) == null ? void 0 : E.exchangeSdp(m));
    };
    e.readyState > 0 && (e.currentTime = 0), e.preload = "auto";
    const { hasVideo: i, hasAudio: s, disableCMS: n, disableP2P: a, statisticsInfoReportInterval: o, playStrategy: c, debug: l, traceId: d } = this.config;
    this.statisticsReporterInterval = window.setInterval(this.reportStatisticsInfo.bind(this), o);
    const { strategies: h = [] } = c || {}, u = h.find((m) => m.type.toUpperCase() === yc.P2P), f = !n && (h.find((m) => m.type.toUpperCase() === yc.CMS) || !u);
    if (S.d(this.TAG, "load url=", f, u), f && (this.rtcCMSPlayer = new on({
      deviceInfo: this.playerDeviceInfo,
      channelMode: yt.CMS,
      element: e,
      // video/audio 标签
      debug: l,
      // 是否打印日志
      zlmsdpUrl: t,
      // 流地址
      audio: s,
      video: i,
      traceId: d,
      encodedInsertableStreams: !0,
      mediaDecodeCallback: (p = this.config.extraOptions) == null ? void 0 : p.mediaDecodeCallback
    }), this.rtcPlayer = this.rtcCMSPlayer, this.initRTCListener(this.rtcCMSPlayer, !1), this.chanelModel = yt.CMS), !a && this.p2pSignalingProxy && u) {
      let { delayTime: m = 0 } = u, g = e;
      f ? (g = e.cloneNode(), g.addEventListener("canplay", this.onP2pStreamPrepare)) : (m = 0, this.chanelModel = yt.P2P), this.p2pInitTimer = setTimeout(() => {
        var x;
        this.rtcP2PPlayer = new on({
          deviceInfo: this.playerDeviceInfo,
          channelMode: yt.P2P,
          element: g,
          debug: l,
          // 是否打印日志
          traceId: d,
          encodedInsertableStreams: !0,
          mediaDecodeCallback: (x = this.config.extraOptions) == null ? void 0 : x.mediaDecodeCallback,
          stunServer: Je.stunAddress,
          p2pSignalingProxy: this.p2pSignalingProxy
        }), this.initRTCListener(this.rtcP2PPlayer, !0);
      }, m * 1e3);
    }
    this.watchNoDataReceived();
  }
  unload() {
    S.i(this.TAG, "rtc unload");
    const e = this.mediaElement;
    e && (e.pause(), e.srcObject = null, e.src = "", e.removeAttribute("src"), e.load()), this.clearReportInterval();
  }
  play() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.play()) ?? Promise.resolve();
  }
  pause() {
    var e;
    (e = this.mediaElement) == null || e.pause(), this.stopWatchNoDataReceived(), clearTimeout(this.p2pInitTimer), this.destroy();
  }
  seek(e) {
    console.info(e);
  }
  get paused() {
    var e;
    return (e = this.mediaElement) == null ? void 0 : e.paused;
  }
  get buffered() {
    var e;
    return (e = this.mediaElement) == null ? void 0 : e.buffered;
  }
  get duration() {
    var e;
    return (e = this.mediaElement) == null ? void 0 : e.duration;
  }
  get volume() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.volume) ?? 0;
  }
  set volume(e) {
    this.mediaElement && (this.mediaElement.volume = e);
  }
  get muted() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.muted) ?? !1;
  }
  set muted(e) {
    this.mediaElement && (this.mediaElement.muted = e);
  }
  get currentTime() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.currentTime) ?? 0;
  }
  set currentTime(e) {
    this.mediaElement ? this.mediaElement.currentTime = e : this.pendingSeekTime = e;
  }
  get mediaInfo() {
    var s;
    let t = {
      mimeType: (this.mediaElement instanceof HTMLAudioElement ? "audio/" : "video/") + ((s = this.mediaDataSource) == null ? void 0 : s.type),
      duration: 0,
      width: 0,
      height: 0
    };
    const i = this.mediaElement;
    return i && (t.duration = Math.floor(i.duration * 1e3), i instanceof HTMLVideoElement && (t.width = i.videoWidth, t.height = i.videoHeight)), t;
  }
  get statisticsInfo() {
    var c;
    let e = {
      playerType: this.type,
      url: (c = this.mediaDataSource) == null ? void 0 : c.url,
      decodedFrames: 0,
      droppedFrames: 0
    };
    const t = this.mediaElement;
    if (!(t instanceof HTMLVideoElement))
      return e;
    let i = !0, s = 0, n = 0;
    const { webkitDecodedFrameCount: a, webkitDroppedFrameCount: o } = t;
    if (t.getVideoPlaybackQuality) {
      let l = t.getVideoPlaybackQuality();
      s = l.totalVideoFrames, n = l.droppedVideoFrames;
    } else a != null ? (s = a, n = o) : i = !1;
    return i && (e.decodedFrames = s, e.droppedFrames = n), e;
  }
  get videoRender() {
    return this.mediaElement;
  }
  get audioRender() {
    return this.mediaElement;
  }
  get metaData() {
    if (this.videoMeta)
      return {
        video: this.videoMeta
      };
  }
  set playbackRate(e) {
    this.fakePlaybackRate = e;
  }
  get playbackRate() {
    return this.fakePlaybackRate;
  }
  clearReportInterval() {
    this.statisticsReporterInterval != null && (window.clearInterval(this.statisticsReporterInterval), this.statisticsReporterInterval = void 0);
  }
  initMediaElement() {
    S.i(this.TAG, "initMediaElement");
    const { videoWrapper: e, muted: t, hasAudio: i } = this.config, s = t || !i ? "muted" : "", n = "player-type";
    let a = this.mediaElement = e == null ? void 0 : e.querySelector("video");
    !a && e && (e.innerHTML = `<video autoplay webkit-playsinline="true" x-webkit-airplay="true" x5-playsinline="true" playsInline ${s} class="${Xs}-player-video-element">Your browser doesn't support HTML5 video.</video>`, a = this.mediaElement = e.querySelector("video")), a.setAttribute(n, this.type), a.style.display = "block", this.attachMediaElement();
  }
  initRTCListener(e, t) {
    if (!e) return;
    const {
      WEBRTC_ICE_CANDIDATE_ERROR: i,
      WEBRTC_ON_REMOTE_STREAMS: s,
      WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: n,
      WEBRTC_ON_LOCAL_STREAM: a,
      CAPTURE_STREAM_FAILED: o,
      WEBRTC_ON_CONNECTION_STATE_CHANGE: c
    } = on.Events;
    [
      i,
      s,
      n,
      a,
      o,
      c
    ].forEach((l) => {
      e.on(l, (...d) => {
        if (l === n) {
          const h = { code: -3, msg: n };
          this.proxyEmit(z.ERROR, Ai.NETWORK_ERROR, h, null);
        } else if (l === c) {
          const h = d[0], { playLimitDuration: u = 0 } = this.config;
          if (S.i(this.TAG, `initRTCListener isP2P=${t} limit=${u}s connectState=`, d), h === _t.connected)
            !t && u > 0 && (clearTimeout(this.playDurationLimitTimer), this.playDurationLimitTimer = setTimeout(this.doPlayDurationLimit, u * 1e3));
          else if (h === _t.failed && (t ? this.destroyP2PPlayer() : this.destroyCMSPlayer(), !this.rtcP2PPlayer && !this.rtcCMSPlayer)) {
            this.stopWatchNoDataReceived();
            const f = { code: -4, msg: "rtc connect failed" };
            this.proxyEmit(z.ERROR, Ai.NETWORK_ERROR, f, null);
          }
        }
        this.proxyEmit(l, ...d);
      });
    }), Object.entries(this.mediaListeners).forEach(([l, d]) => {
      e.on(l, d);
    });
  }
  destroyP2PPlayer() {
    var t, i, s;
    clearTimeout(this.p2pInitTimer);
    const e = (t = this.rtcP2PPlayer) == null ? void 0 : t.mediaElement;
    e == null || e.removeEventListener("canplay", this.onP2pStreamPrepare), (i = this.rtcP2PPlayer) == null || i.destroy(), this.rtcP2PPlayer = void 0, (s = this.p2pSignalingProxy) == null || s.destroy(), this.p2pSignalingProxy = void 0;
  }
  destroyCMSPlayer() {
    var e, t;
    this.playerDeviceInfo.seekParam || (e = this.signalingProxy) == null || e.stopCmsLivePreview(), (t = this.rtcCMSPlayer) == null || t.destroy(), this.rtcCMSPlayer = void 0;
  }
  destroyRTCPlayer() {
    this.destroyP2PPlayer(), this.destroyCMSPlayer();
  }
  proxyEmit(e, ...t) {
    var i;
    (i = this.emitter) == null || i.emit(e, ...t);
  }
  onvLoadedMetadata() {
    this.pendingSeekTime != null && this.mediaElement && (this.mediaElement.currentTime = this.pendingSeekTime, this.pendingSeekTime = void 0), this.proxyEmit(z.MEDIA_INFO, this.mediaInfo);
  }
  onvCanPlay() {
    var t;
    S.i(this.TAG, "onvCanPlay");
    const e = this.mediaElement;
    if (e) {
      if (this.mediaListeners && (e == null || e.removeEventListener("canplay", this.mediaListeners.canPlay)), (t = this.mediaElement) != null && t.autoplay) {
        let i = this.mediaElement.play();
        i !== void 0 && i.then(() => {
        }).catch((s) => {
          S.e(this.TAG, "Events.CAN_PLAY canot autoplay！", (s == null ? void 0 : s.message) || (s == null ? void 0 : s.stack) || (s == null ? void 0 : s.toString())), this.pause();
        });
      }
      this.proxyEmit(z.CAN_PLAY);
    }
  }
  onvLoadedData() {
    var e;
    S.i(this.TAG, "on loadeddata event"), this.mediaListeners && ((e = this.mediaElement) == null || e.removeEventListener("canplay", this.mediaListeners.canPlay)), this.onvCanPlay();
  }
  onvEnded() {
    this.proxyEmit(z.PLAY_ENDED);
  }
  onvError(e) {
    var i;
    let t = ((i = this.mediaElement) == null ? void 0 : i.error) || {};
    this.proxyEmit(z.ERROR, "MEDIA_ERROR", e, t);
  }
  onvPlaying() {
    this.proxyEmit(z.PLAYING);
  }
  onvTimeupdate() {
    var i;
    this.watchNoDataReceived(), this.paused || (this.onvPlaying(), this.watchVideoResolutionChange());
    const e = Math.round(this.currentTime * 1e3), t = ((i = this.rtcPlayer) == null ? void 0 : i.absTimestamp) ?? e;
    this.proxyEmit(z.TIME_UPDATE, t, e);
  }
  reportStatisticsInfo() {
    this.proxyEmit(z.STATISTICS_INFO, this.statisticsInfo);
  }
  /**
   * 一定时间内没有收到数据，做超时处理
   * @returns
   */
  watchNoDataReceived() {
    this.stopWatchNoDataReceived();
    let { bufferWaitTimeMS: e } = this.config;
    this.noDataReceivedTimer = setTimeout(() => {
      S.e(this.TAG, `webrtc Long time no data received. ${e}ms`);
      const t = { code: -2, msg: "Long time no data received, rtc timeout" };
      this.proxyEmit(z.ERROR, Ai.NETWORK_ERROR, t, null);
    }, e);
  }
  stopWatchNoDataReceived() {
    clearTimeout(this.noDataReceivedTimer);
  }
}
class yg {
  static install() {
    Object.setPrototypeOf = Object.setPrototypeOf || function(e, t) {
      return e.__proto__ = t, e;
    }, Object.assign = Object.assign || function(e) {
      if (e == null)
        throw new TypeError("Cannot convert undefined or null to object");
      let t = Object(e);
      for (let i = 1; i < arguments.length; i++) {
        let s = arguments[i];
        if (s != null)
          for (let n in s)
            s.hasOwnProperty(n) && (t[n] = s[n]);
      }
      return t;
    }, String.prototype.startsWith || Object.defineProperty(String.prototype, "startsWith", {
      value: function(e, t) {
        let i = t > 0 ? t | 0 : 0;
        return this.substring(i, i + e.length) === e;
      }
    });
  }
}
yg.install();
class xg {
  constructor() {
    this._firstCheckpoint = 0, this._lastCheckpoint = 0, this._intervalBytes = 0, this._totalBytes = 0, this._lastSecondBytes = 0, self.performance && self.performance.now ? this._now = self.performance.now.bind(self.performance) : this._now = Date.now;
  }
  reset() {
    this._firstCheckpoint = this._lastCheckpoint = 0, this._totalBytes = this._intervalBytes = 0, this._lastSecondBytes = 0;
  }
  addBytes(e) {
    this._firstCheckpoint === 0 ? (this._firstCheckpoint = this._now(), this._lastCheckpoint = this._firstCheckpoint, this._intervalBytes += e, this._totalBytes += e) : this._now() - this._lastCheckpoint < 1e3 ? (this._intervalBytes += e, this._totalBytes += e) : (this._lastSecondBytes = this._intervalBytes, this._intervalBytes = e, this._totalBytes += e, this._lastCheckpoint = this._now());
  }
  get currentKBps() {
    this.addBytes(0);
    let e = (this._now() - this._lastCheckpoint) / 1e3;
    return e == 0 && (e = 1), this._intervalBytes / e / 1024;
  }
  get lastSecondKBps() {
    return this.addBytes(0), this._lastSecondBytes !== 0 ? this._lastSecondBytes / 1024 : this._now() - this._lastCheckpoint >= 500 ? this.currentKBps : 0;
  }
  get averageKBps() {
    let e = (this._now() - this._firstCheckpoint) / 1e3;
    return this._totalBytes / e / 1024;
  }
}
let ye = {};
function _b() {
  let r = self.navigator.userAgent.toLowerCase(), e = /(edge)\/([\w.]+)/.exec(r) || /(opr)[\/]([\w.]+)/.exec(r) || /(chrome)[ \/]([\w.]+)/.exec(r) || /(iemobile)[\/]([\w.]+)/.exec(r) || /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(r) || /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(r) || /(webkit)[ \/]([\w.]+)/.exec(r) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(r) || /(msie) ([\w.]+)/.exec(r) || r.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec(r) || r.indexOf("compatible") < 0 && /(firefox)[ \/]([\w.]+)/.exec(r) || [], t = /(ipad)/.exec(r) || /(ipod)/.exec(r) || /(windows phone)/.exec(r) || /(iphone)/.exec(r) || /(kindle)/.exec(r) || /(android)/.exec(r) || /(windows)/.exec(r) || /(mac)/.exec(r) || /(linux)/.exec(r) || /(cros)/.exec(r) || [], i = {
    browser: e[5] || e[3] || e[1] || "",
    version: e[2] || e[4] || "0",
    majorVersion: e[4] || e[2] || "0",
    platform: t[0] || ""
  }, s = {};
  if (i.browser) {
    s[i.browser] = !0;
    let n = i.majorVersion.split(".");
    s.version = {
      major: parseInt(i.majorVersion, 10),
      string: i.version
    }, n.length > 1 && (s.version.minor = parseInt(n[1], 10)), n.length > 2 && (s.version.build = parseInt(n[2], 10));
  }
  if (i.platform && (s[i.platform] = !0), (s.chrome || s.opr || s.safari) && (s.webkit = !0), s.rv || s.iemobile) {
    s.rv && delete s.rv;
    let n = "msie";
    i.browser = n, s[n] = !0;
  }
  if (s.edge) {
    delete s.edge;
    let n = "msedge";
    i.browser = n, s[n] = !0;
  }
  if (s.opr) {
    let n = "opera";
    i.browser = n, s[n] = !0;
  }
  if (s.safari && s.android) {
    let n = "android";
    i.browser = n, s[n] = !0;
  }
  s.name = i.browser, s.platform = i.platform;
  for (let n in ye)
    ye.hasOwnProperty(n) && delete ye[n];
  s.mobile = r.indexOf("mobile") > -1 || s.iphone || s.ipad || s.ipod || s.android, s.electron = r.indexOf("electron") > -1, Object.assign(ye, s);
}
_b();
class Qu extends kn {
  static isSupported() {
    try {
      let e = ye.msedge && ye.version.minor >= 15048, t = ye.msedge ? e : !0;
      return self.fetch && self.ReadableStream && t;
    } catch {
      return !1;
    }
  }
  constructor(e, t) {
    super("fetch-stream-loader"), this.TAG = "FetchStreamLoader", this._seekHandler = e, this._config = t, this._needStash = !0, this._requestAbort = !1, this._abortController = null, this._contentLength = null, this._receivedLength = 0;
  }
  destroy() {
    this.isWorking() && this.abort(), super.destroy();
  }
  open(e, t) {
    this._dataSource = e, this._range = t;
    let i = e.url;
    this._config.reuseRedirectedURL && e.redirectedURL != null && (i = e.redirectedURL);
    let s = this._seekHandler.getConfig(i, t), n = new self.Headers();
    if (typeof s.headers == "object") {
      let o = s.headers;
      for (let c in o)
        o.hasOwnProperty(c) && n.append(c, o[c]);
    }
    let a = {
      method: "GET",
      headers: n,
      mode: "cors",
      cache: "default",
      // The default policy of Fetch API in the whatwg standard
      // Safari incorrectly indicates 'no-referrer' as default policy, fuck it
      referrerPolicy: "no-referrer-when-downgrade"
    };
    if (typeof this._config.headers == "object")
      for (let o in this._config.headers)
        n.append(o, this._config.headers[o]);
    e.cors === !1 && (a.mode = "same-origin"), e.withCredentials && (a.credentials = "include"), e.referrerPolicy && (a.referrerPolicy = e.referrerPolicy), self.AbortController && (this._abortController = new self.AbortController(), a.signal = this._abortController.signal), this._status = fe.kConnecting, self.fetch(s.url, a).then((o) => {
      if (this._requestAbort) {
        this._status = fe.kIdle, o.body.cancel();
        return;
      }
      if (o.ok && o.status >= 200 && o.status <= 299) {
        if (o.url !== s.url && this._onURLRedirect) {
          let l = this._seekHandler.removeURLParameters(o.url);
          this._onURLRedirect(l);
        }
        let c = o.headers.get("Content-Length");
        return c != null && (this._contentLength = parseInt(c), this._contentLength !== 0 && this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength)), this._pump.call(this, o.body.getReader());
      } else if (this._status = fe.kError, this._onError)
        this._onError(Ue.HTTP_STATUS_CODE_INVALID, { code: o.status, msg: o.statusText });
      else
        throw new At("FetchStreamLoader: Http code invalid, " + o.status + " " + o.statusText);
    }).catch((o) => {
      if (!(this._abortController && this._abortController.signal.aborted))
        if (this._status = fe.kError, this._onError)
          this._onError(Ue.EXCEPTION, { code: -1, msg: o.message });
        else
          throw o;
    });
  }
  abort() {
    if (this._requestAbort = !0, this._abortController)
      try {
        this._abortController.abort();
      } catch {
        S.d(this.TAG, "abort error", error);
      }
  }
  _pump(e) {
    return e.read().then((t) => {
      if (t.done)
        if (this._contentLength !== null && this._receivedLength < this._contentLength) {
          this._status = fe.kError;
          let i = Ue.EARLY_EOF, s = { code: -1, msg: "Fetch stream meet Early-EOF" };
          if (this._onError)
            this._onError(i, s);
          else
            throw new At(s.msg);
        } else
          this._status = fe.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
      else {
        if (this._abortController && this._abortController.signal.aborted) {
          this._status = fe.kComplete;
          return;
        } else if (this._requestAbort === !0)
          return this._status = fe.kComplete, e.cancel();
        this._status = fe.kBuffering;
        let i = t.value.buffer, s = this._range.from + this._receivedLength;
        this._receivedLength += i.byteLength, this._onDataArrival && this._onDataArrival(i, s, this._receivedLength), this._pump(e);
      }
    }).catch((t) => {
      if (this._abortController && this._abortController.signal.aborted) {
        this._status = fe.kComplete;
        return;
      }
      if (t.code === 11 && ye.msedge)
        return;
      this._status = fe.kError;
      let i = 0, s = null;
      if ((t.code === 19 || t.message === "network error") && // NETWORK_ERR
      (this._contentLength === null || this._contentLength !== null && this._receivedLength < this._contentLength) ? (i = Ue.EARLY_EOF, s = { code: t.code, msg: "Fetch stream meet Early-EOF" }) : (i = Ue.EXCEPTION, s = { code: t.code, msg: t.message }), this._onError)
        this._onError(i, s);
      else
        throw new At(s.msg);
    });
  }
}
class Ju extends kn {
  static isSupported() {
    try {
      let e = new XMLHttpRequest();
      return e.open("GET", "https://example.com", !0), e.responseType = "moz-chunked-arraybuffer", e.responseType === "moz-chunked-arraybuffer";
    } catch (e) {
      return S.w("MozChunkedLoader", e.message), !1;
    }
  }
  constructor(e, t) {
    super("xhr-moz-chunked-loader"), this.TAG = "MozChunkedLoader", this._seekHandler = e, this._config = t, this._needStash = !0, this._xhr = null, this._requestAbort = !1, this._contentLength = null, this._receivedLength = 0;
  }
  destroy() {
    this.isWorking() && this.abort(), this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onloadend = null, this._xhr.onerror = null, this._xhr = null), super.destroy();
  }
  open(e, t) {
    this._dataSource = e, this._range = t;
    let i = e.url;
    this._config.reuseRedirectedURL && e.redirectedURL != null && (i = e.redirectedURL);
    let s = this._seekHandler.getConfig(i, t);
    this._requestURL = s.url;
    let n = this._xhr = new XMLHttpRequest();
    if (n.open("GET", s.url, !0), n.responseType = "moz-chunked-arraybuffer", n.onreadystatechange = this._onReadyStateChange.bind(this), n.onprogress = this._onProgress.bind(this), n.onloadend = this._onLoadEnd.bind(this), n.onerror = this._onXhrError.bind(this), e.withCredentials && (n.withCredentials = !0), typeof s.headers == "object") {
      let a = s.headers;
      for (let o in a)
        a.hasOwnProperty(o) && n.setRequestHeader(o, a[o]);
    }
    if (typeof this._config.headers == "object") {
      let a = this._config.headers;
      for (let o in a)
        a.hasOwnProperty(o) && n.setRequestHeader(o, a[o]);
    }
    this._status = fe.kConnecting, n.send();
  }
  abort() {
    this._requestAbort = !0, this._xhr && this._xhr.abort(), this._status = fe.kComplete;
  }
  _onReadyStateChange(e) {
    let t = e.target;
    if (t.readyState === 2) {
      if (t.responseURL != null && t.responseURL !== this._requestURL && this._onURLRedirect) {
        let i = this._seekHandler.removeURLParameters(t.responseURL);
        this._onURLRedirect(i);
      }
      if (t.status !== 0 && (t.status < 200 || t.status > 299))
        if (this._status = fe.kError, this._onError)
          this._onError(Ue.HTTP_STATUS_CODE_INVALID, { code: t.status, msg: t.statusText });
        else
          throw new At("MozChunkedLoader: Http code invalid, " + t.status + " " + t.statusText);
      else
        this._status = fe.kBuffering;
    }
  }
  _onProgress(e) {
    if (this._status === fe.kError)
      return;
    this._contentLength === null && e.total !== null && e.total !== 0 && (this._contentLength = e.total, this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength));
    let t = e.target.response, i = this._range.from + this._receivedLength;
    this._receivedLength += t.byteLength, this._onDataArrival && this._onDataArrival(t, i, this._receivedLength);
  }
  _onLoadEnd(e) {
    if (this._requestAbort === !0) {
      this._requestAbort = !1;
      return;
    } else if (this._status === fe.kError)
      return;
    this._status = fe.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1);
  }
  _onXhrError(e) {
    this._status = fe.kError;
    let t = 0, i = null;
    if (this._contentLength && e.loaded < this._contentLength ? (t = Ue.EARLY_EOF, i = { code: -1, msg: "Moz-Chunked stream meet Early-Eof" }) : (t = Ue.EXCEPTION, i = { code: -1, msg: e.constructor.name + " " + e.type }), this._onError)
      this._onError(t, i);
    else
      throw new At(i.msg);
  }
}
class t0 extends kn {
  static isSupported() {
    try {
      let e = new XMLHttpRequest();
      return e.open("GET", "https://example.com", !0), e.responseType = "arraybuffer", e.responseType === "arraybuffer";
    } catch (e) {
      return S.w("RangeLoader", e.message), !1;
    }
  }
  constructor(e, t) {
    super("xhr-range-loader"), this.TAG = "RangeLoader", this._seekHandler = e, this._config = t, this._needStash = !1, this._chunkSizeKBList = [
      128,
      256,
      384,
      512,
      768,
      1024,
      1536,
      2048,
      3072,
      4096,
      5120,
      6144,
      7168,
      8192
    ], this._currentChunkSizeKB = 384, this._currentSpeedNormalized = 0, this._zeroSpeedChunkCount = 0, this._xhr = null, this._speedSampler = new xg(), this._requestAbort = !1, this._waitForTotalLength = !1, this._totalLengthReceived = !1, this._currentRequestURL = null, this._currentRedirectedURL = null, this._currentRequestRange = null, this._totalLength = null, this._contentLength = null, this._receivedLength = 0, this._lastTimeLoaded = 0;
  }
  destroy() {
    this.isWorking() && this.abort(), this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onload = null, this._xhr.onerror = null, this._xhr = null), super.destroy();
  }
  get currentSpeed() {
    return this._speedSampler.lastSecondKBps;
  }
  open(e, t) {
    this._dataSource = e, this._range = t, this._status = fe.kConnecting;
    let i = !1;
    this._dataSource.filesize != null && this._dataSource.filesize !== 0 && (i = !0, this._totalLength = this._dataSource.filesize), !this._totalLengthReceived && !i ? (this._waitForTotalLength = !0, this._internalOpen(this._dataSource, { from: 0, to: -1 })) : this._openSubRange();
  }
  _openSubRange() {
    let e = this._currentChunkSizeKB * 1024, t = this._range.from + this._receivedLength, i = t + e;
    this._contentLength != null && i - this._range.from >= this._contentLength && (i = this._range.from + this._contentLength - 1), this._currentRequestRange = { from: t, to: i }, this._internalOpen(this._dataSource, this._currentRequestRange);
  }
  _internalOpen(e, t) {
    this._lastTimeLoaded = 0;
    let i = e.url;
    this._config.reuseRedirectedURL && (this._currentRedirectedURL != null ? i = this._currentRedirectedURL : e.redirectedURL != null && (i = e.redirectedURL));
    let s = this._seekHandler.getConfig(i, t);
    this._currentRequestURL = s.url;
    let n = this._xhr = new XMLHttpRequest();
    if (n.open("GET", s.url, !0), n.responseType = "arraybuffer", n.onreadystatechange = this._onReadyStateChange.bind(this), n.onprogress = this._onProgress.bind(this), n.onload = this._onLoad.bind(this), n.onerror = this._onXhrError.bind(this), e.withCredentials && (n.withCredentials = !0), typeof s.headers == "object") {
      let a = s.headers;
      for (let o in a)
        a.hasOwnProperty(o) && n.setRequestHeader(o, a[o]);
    }
    if (typeof this._config.headers == "object") {
      let a = this._config.headers;
      for (let o in a)
        a.hasOwnProperty(o) && n.setRequestHeader(o, a[o]);
    }
    n.send();
  }
  abort() {
    this._requestAbort = !0, this._internalAbort(), this._status = fe.kComplete;
  }
  _internalAbort() {
    this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onload = null, this._xhr.onerror = null, this._xhr.abort(), this._xhr = null);
  }
  _onReadyStateChange(e) {
    let t = e.target;
    if (t.readyState === 2) {
      if (t.responseURL != null) {
        let i = this._seekHandler.removeURLParameters(t.responseURL);
        t.responseURL !== this._currentRequestURL && i !== this._currentRedirectedURL && (this._currentRedirectedURL = i, this._onURLRedirect && this._onURLRedirect(i));
      }
      if (t.status >= 200 && t.status <= 299) {
        if (this._waitForTotalLength)
          return;
        this._status = fe.kBuffering;
      } else if (this._status = fe.kError, this._onError)
        this._onError(Ue.HTTP_STATUS_CODE_INVALID, { code: t.status, msg: t.statusText });
      else
        throw new At("RangeLoader: Http code invalid, " + t.status + " " + t.statusText);
    }
  }
  _onProgress(e) {
    if (this._status === fe.kError)
      return;
    if (this._contentLength === null) {
      let i = !1;
      if (this._waitForTotalLength) {
        this._waitForTotalLength = !1, this._totalLengthReceived = !0, i = !0;
        let s = e.total;
        this._internalAbort(), s != null & s !== 0 && (this._totalLength = s);
      }
      if (this._range.to === -1 ? this._contentLength = this._totalLength - this._range.from : this._contentLength = this._range.to - this._range.from + 1, i) {
        this._openSubRange();
        return;
      }
      this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength);
    }
    let t = e.loaded - this._lastTimeLoaded;
    this._lastTimeLoaded = e.loaded, this._speedSampler.addBytes(t);
  }
  _normalizeSpeed(e) {
    let t = this._chunkSizeKBList, i = t.length - 1, s = 0, n = 0, a = i;
    if (e < t[0])
      return t[0];
    for (; n <= a; ) {
      if (s = n + Math.floor((a - n) / 2), s === i || e >= t[s] && e < t[s + 1])
        return t[s];
      t[s] < e ? n = s + 1 : a = s - 1;
    }
  }
  _onLoad(e) {
    if (this._status === fe.kError)
      return;
    if (this._waitForTotalLength) {
      this._waitForTotalLength = !1;
      return;
    }
    this._lastTimeLoaded = 0;
    let t = this._speedSampler.lastSecondKBps;
    if (t === 0 && (this._zeroSpeedChunkCount++, this._zeroSpeedChunkCount >= 3 && (t = this._speedSampler.currentKBps)), t !== 0) {
      let a = this._normalizeSpeed(t);
      this._currentSpeedNormalized !== a && (this._currentSpeedNormalized = a, this._currentChunkSizeKB = a);
    }
    let i = e.target.response, s = this._range.from + this._receivedLength;
    this._receivedLength += i.byteLength;
    let n = !1;
    this._contentLength != null && this._receivedLength < this._contentLength ? this._openSubRange() : n = !0, this._onDataArrival && this._onDataArrival(i, s, this._receivedLength), n && (this._status = fe.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1));
  }
  _onXhrError(e) {
    this._status = fe.kError;
    let t = 0, i = null;
    if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength ? (t = Ue.EARLY_EOF, i = { code: -1, msg: "RangeLoader meet Early-Eof" }) : (t = Ue.EXCEPTION, i = { code: -1, msg: e.constructor.name + " " + e.type }), this._onError)
      this._onError(t, i);
    else
      throw new At(i.msg);
  }
}
class yb extends kn {
  static isSupported() {
    try {
      return typeof self.WebSocket < "u";
    } catch {
      return !1;
    }
  }
  constructor() {
    super("websocket-loader"), this.TAG = "WebSocketLoader", this._needStash = !0, this._ws = null, this._requestAbort = !1, this._receivedLength = 0;
  }
  destroy() {
    this._ws && this.abort(), super.destroy();
  }
  open(e) {
    try {
      let t = this._ws = new self.WebSocket(e.url);
      t.binaryType = "arraybuffer", t.onopen = this._onWebSocketOpen.bind(this), t.onclose = this._onWebSocketClose.bind(this), t.onmessage = this._onWebSocketMessage.bind(this), t.onerror = this._onWebSocketError.bind(this), this._status = fe.kConnecting;
    } catch (t) {
      this._status = fe.kError;
      let i = { code: t.code, msg: t.message };
      if (this._onError)
        this._onError(Ue.EXCEPTION, i);
      else
        throw new At(i.msg);
    }
  }
  abort() {
    let e = this._ws;
    e && (e.readyState === 0 || e.readyState === 1) && (this._requestAbort = !0, e.close()), this._ws = null, this._status = fe.kComplete;
  }
  _onWebSocketOpen(e) {
    this._status = fe.kBuffering;
  }
  _onWebSocketClose(e) {
    if (this._requestAbort === !0) {
      this._requestAbort = !1;
      return;
    }
    this._status = fe.kComplete, this._onComplete && this._onComplete(0, this._receivedLength - 1);
  }
  _onWebSocketMessage(e) {
    if (e.data instanceof ArrayBuffer)
      this._dispatchArrayBuffer(e.data);
    else if (e.data instanceof Blob) {
      let t = new FileReader();
      t.onload = () => {
        this._dispatchArrayBuffer(t.result);
      }, t.readAsArrayBuffer(e.data);
    } else {
      this._status = fe.kError;
      let t = { code: -1, msg: "Unsupported WebSocket message type: " + e.data.constructor.name };
      if (this._onError)
        this._onError(Ue.EXCEPTION, t);
      else
        throw new At(t.msg);
    }
  }
  _dispatchArrayBuffer(e) {
    let t = e, i = this._receivedLength;
    this._receivedLength += t.byteLength, this._onDataArrival && this._onDataArrival(t, i, this._receivedLength);
  }
  _onWebSocketError(e) {
    this._status = fe.kError;
    let t = {
      code: e.code,
      msg: e.message
    };
    if (this._onError)
      this._onError(Ue.EXCEPTION, t);
    else
      throw new At(t.msg);
  }
}
class xb {
  constructor(e) {
    this._zeroStart = e || !1;
  }
  getConfig(e, t) {
    let i = {};
    if (t.from !== 0 || t.to !== -1) {
      let s;
      t.to !== -1 ? s = `bytes=${t.from.toString()}-${t.to.toString()}` : s = `bytes=${t.from.toString()}-`, i.Range = s;
    } else this._zeroStart && (i.Range = "bytes=0-");
    return {
      url: e,
      headers: i
    };
  }
  removeURLParameters(e) {
    return e;
  }
}
class vb {
  constructor(e, t) {
    this._startName = e, this._endName = t;
  }
  getConfig(e, t) {
    let i = e;
    if (t.from !== 0 || t.to !== -1) {
      let s = !0;
      i.indexOf("?") === -1 && (i += "?", s = !1), s && (i += "&"), i += `${this._startName}=${t.from.toString()}`, t.to !== -1 && (i += `&${this._endName}=${t.to.toString()}`);
    }
    return {
      url: i,
      headers: {}
    };
  }
  removeURLParameters(e) {
    let t = e.split("?")[0], i, s = e.indexOf("?");
    s !== -1 && (i = e.substring(s + 1));
    let n = "";
    if (i != null && i.length > 0) {
      let a = i.split("&");
      for (let o = 0; o < a.length; o++) {
        let c = a[o].split("="), l = o > 0;
        c[0] !== this._startName && c[0] !== this._endName && (l && (n += "&"), n += a[o]);
      }
    }
    return n.length === 0 ? t : t + "?" + n;
  }
}
class vc {
  constructor(e, t, i) {
    this.TAG = "IOController", this._config = t, this._extraData = i, this._stashInitialSize = 64 * 1024, t.stashInitialSize != null && t.stashInitialSize > 0 && (this._stashInitialSize = t.stashInitialSize), this._stashUsed = 0, this._stashSize = this._stashInitialSize, this._bufferSize = Math.max(this._stashSize, 1024 * 1024 * 3), this._stashBuffer = new ArrayBuffer(this._bufferSize), this._stashByteStart = 0, this._enableStash = !0, t.enableStashBuffer === !1 && (this._enableStash = !1), this._loader = null, this._loaderClass = null, this._seekHandler = null, this._dataSource = e, this._isWebSocketURL = /wss?:\/\/(.+?)/.test(e.url), this._refTotalLength = e.filesize ? e.filesize : null, this._totalLength = this._refTotalLength, this._fullRequestFlag = !1, this._currentRange = null, this._redirectedURL = null, this._speedNormalized = 0, this._speedSampler = new xg(), this._speedNormalizeList = [32, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096], this._isEarlyEofReconnecting = !1, this._paused = !1, this._resumeFrom = 0, this._onDataArrival = null, this._onSeeked = null, this._onError = null, this._onComplete = null, this._onRedirect = null, this._onRecoveredEarlyEof = null, this._selectSeekHandler(), this._selectLoader(), this._createLoader();
  }
  destroy() {
    this._loader.isWorking() && this._loader.abort(), this._loader.destroy(), this._loader = null, this._loaderClass = null, this._dataSource = null, this._stashBuffer = null, this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0, this._currentRange = null, this._speedSampler = null, this._isEarlyEofReconnecting = !1, this._onDataArrival = null, this._onSeeked = null, this._onError = null, this._onComplete = null, this._onRedirect = null, this._onRecoveredEarlyEof = null, this._extraData = null;
  }
  isWorking() {
    return this._loader && this._loader.isWorking() && !this._paused;
  }
  isPaused() {
    return this._paused;
  }
  get status() {
    return this._loader.status;
  }
  get extraData() {
    return this._extraData;
  }
  set extraData(e) {
    this._extraData = e;
  }
  // prototype: function onDataArrival(chunks: ArrayBuffer, byteStart: number): number
  get onDataArrival() {
    return this._onDataArrival;
  }
  set onDataArrival(e) {
    this._onDataArrival = e;
  }
  get onSeeked() {
    return this._onSeeked;
  }
  set onSeeked(e) {
    this._onSeeked = e;
  }
  // prototype: function onError(type: number, info: {code: number, msg: string}): void
  get onError() {
    return this._onError;
  }
  set onError(e) {
    this._onError = e;
  }
  get onComplete() {
    return this._onComplete;
  }
  set onComplete(e) {
    this._onComplete = e;
  }
  get onRedirect() {
    return this._onRedirect;
  }
  set onRedirect(e) {
    this._onRedirect = e;
  }
  get onRecoveredEarlyEof() {
    return this._onRecoveredEarlyEof;
  }
  set onRecoveredEarlyEof(e) {
    this._onRecoveredEarlyEof = e;
  }
  get currentURL() {
    return this._dataSource.url;
  }
  get hasRedirect() {
    return this._redirectedURL != null || this._dataSource.redirectedURL != null;
  }
  get currentRedirectedURL() {
    return this._redirectedURL || this._dataSource.redirectedURL;
  }
  // in KB/s
  get currentSpeed() {
    return this._loaderClass === t0 ? this._loader.currentSpeed : this._speedSampler.lastSecondKBps;
  }
  get loaderType() {
    return this._loader.type;
  }
  _selectSeekHandler() {
    let e = this._config;
    if (e.seekType === "range")
      this._seekHandler = new xb(this._config.rangeLoadZeroStart);
    else if (e.seekType === "param") {
      let t = e.seekParamStart || "bstart", i = e.seekParamEnd || "bend";
      this._seekHandler = new vb(t, i);
    } else if (e.seekType === "custom") {
      if (typeof e.customSeekHandler != "function")
        throw new Yi("Custom seekType specified in config but invalid customSeekHandler!");
      this._seekHandler = new e.customSeekHandler();
    } else
      throw new Yi(`Invalid seekType in config: ${e.seekType}`);
  }
  _selectLoader() {
    if (this._config.customLoader != null)
      this._loaderClass = this._config.customLoader;
    else if (this._isWebSocketURL)
      this._loaderClass = yb;
    else if (Qu.isSupported())
      this._loaderClass = Qu;
    else if (Ju.isSupported())
      this._loaderClass = Ju;
    else if (t0.isSupported())
      this._loaderClass = t0;
    else
      throw new At("Your browser doesn't support xhr with arraybuffer responseType!");
  }
  _createLoader() {
    this._loader = new this._loaderClass(this._seekHandler, this._config), this._loader.needStashBuffer === !1 && (this._enableStash = !1), this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this), this._loader.onURLRedirect = this._onURLRedirect.bind(this), this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this), this._loader.onComplete = this._onLoaderComplete.bind(this), this._loader.onError = this._onLoaderError.bind(this);
  }
  open(e) {
    this._currentRange = { from: 0, to: -1 }, e && (this._currentRange.from = e), this._speedSampler.reset(), e || (this._fullRequestFlag = !0);
    try {
      this._loader.open(this._dataSource, Object.assign({}, this._currentRange));
    } catch {
    }
  }
  abort() {
    this._loader.abort(), this._paused && (this._paused = !1, this._resumeFrom = 0);
  }
  pause() {
    this.isWorking() && (this._loader.abort(), this._stashUsed !== 0 ? (this._resumeFrom = this._stashByteStart, this._currentRange.to = this._stashByteStart - 1) : this._resumeFrom = this._currentRange.to + 1, this._stashUsed = 0, this._stashByteStart = 0, this._paused = !0);
  }
  resume() {
    if (this._paused) {
      this._paused = !1;
      let e = this._resumeFrom;
      this._resumeFrom = 0, this._internalSeek(e, !0);
    }
  }
  seek(e) {
    this._paused = !1, this._stashUsed = 0, this._stashByteStart = 0, this._internalSeek(e, !0);
  }
  /**
   * When seeking request is from media seeking, unconsumed stash data should be dropped
   * However, stash data shouldn't be dropped if seeking requested from http reconnection
   *
   * @dropUnconsumed: Ignore and discard all unconsumed data in stash buffer
   */
  _internalSeek(e, t) {
    this._loader.isWorking() && this._loader.abort(), this._flushStashBuffer(t), this._loader.destroy(), this._loader = null;
    let i = { from: e, to: -1 };
    this._currentRange = { from: i.from, to: -1 }, this._speedSampler.reset(), this._stashSize = this._stashInitialSize, this._createLoader();
    try {
      this._loader.open(this._dataSource, i);
    } catch {
    }
    this._onSeeked && this._onSeeked();
  }
  updateUrl(e) {
    if (!e || typeof e != "string" || e.length === 0)
      throw new Yi("Url must be a non-empty string!");
    this._dataSource.url = e;
  }
  _expandBuffer(e) {
    let t = this._stashSize;
    for (; t + 1024 * 1024 * 1 < e; )
      t *= 2;
    if (t += 1024 * 1024 * 1, t === this._bufferSize)
      return;
    let i = new ArrayBuffer(t);
    if (this._stashUsed > 0) {
      let s = new Uint8Array(this._stashBuffer, 0, this._stashUsed);
      new Uint8Array(i, 0, t).set(s, 0);
    }
    this._stashBuffer = i, this._bufferSize = t;
  }
  _normalizeSpeed(e) {
    let t = this._speedNormalizeList, i = t.length - 1, s = 0, n = 0, a = i;
    if (e < t[0])
      return t[0];
    for (; n <= a; ) {
      if (s = n + Math.floor((a - n) / 2), s === i || e >= t[s] && e < t[s + 1])
        return t[s];
      t[s] < e ? n = s + 1 : a = s - 1;
    }
  }
  _adjustStashSize(e) {
    let t = 0;
    this._config.isLive ? t = e / 8 : e < 512 ? t = e : e >= 512 && e <= 1024 ? t = Math.floor(e * 1.5) : t = e * 2, t > 8192 && (t = 8192);
    let i = t * 1024 + 1024 * 1024 * 1;
    this._bufferSize < i && this._expandBuffer(i), this._stashSize = t * 1024;
  }
  _dispatchChunks(e, t) {
    return this._currentRange.to = t + e.byteLength - 1, this._onDataArrival(e, t);
  }
  _onURLRedirect(e) {
    this._redirectedURL = e, this._onRedirect && this._onRedirect(e);
  }
  _onContentLengthKnown(e) {
    e && this._fullRequestFlag && (this._totalLength = e, this._fullRequestFlag = !1);
  }
  _onLoaderChunkArrival(e, t, i) {
    if (!this._onDataArrival)
      throw new qe("IOController: No existing consumer (onDataArrival) callback!");
    if (this._paused)
      return;
    this._isEarlyEofReconnecting && (this._isEarlyEofReconnecting = !1, this._onRecoveredEarlyEof && this._onRecoveredEarlyEof()), this._speedSampler.addBytes(e.byteLength);
    let s = this._speedSampler.lastSecondKBps;
    if (s !== 0) {
      let n = this._normalizeSpeed(s);
      this._speedNormalized !== n && (this._speedNormalized = n, this._adjustStashSize(n));
    }
    if (this._enableStash)
      if (this._stashUsed === 0 && this._stashByteStart === 0 && (this._stashByteStart = t), this._stashUsed + e.byteLength <= this._stashSize)
        new Uint8Array(this._stashBuffer, 0, this._stashSize).set(new Uint8Array(e), this._stashUsed), this._stashUsed += e.byteLength;
      else {
        let n = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
        if (this._stashUsed > 0) {
          let a = this._stashBuffer.slice(0, this._stashUsed), o = this._dispatchChunks(a, this._stashByteStart);
          if (o < a.byteLength) {
            if (o > 0) {
              let c = new Uint8Array(a, o);
              n.set(c, 0), this._stashUsed = c.byteLength, this._stashByteStart += o;
            }
          } else
            this._stashUsed = 0, this._stashByteStart += o;
          this._stashUsed + e.byteLength > this._bufferSize && (this._expandBuffer(this._stashUsed + e.byteLength), n = new Uint8Array(this._stashBuffer, 0, this._bufferSize)), n.set(new Uint8Array(e), this._stashUsed), this._stashUsed += e.byteLength;
        } else {
          let a = this._dispatchChunks(e, t);
          if (a < e.byteLength) {
            let o = e.byteLength - a;
            o > this._bufferSize && (this._expandBuffer(o), n = new Uint8Array(this._stashBuffer, 0, this._bufferSize)), n.set(new Uint8Array(e, a), 0), this._stashUsed += o, this._stashByteStart = t + a;
          }
        }
      }
    else if (this._stashUsed === 0) {
      let n = this._dispatchChunks(e, t);
      if (n < e.byteLength) {
        let a = e.byteLength - n;
        a > this._bufferSize && this._expandBuffer(a), new Uint8Array(this._stashBuffer, 0, this._bufferSize).set(new Uint8Array(e, n), 0), this._stashUsed += a, this._stashByteStart = t + n;
      }
    } else {
      this._stashUsed + e.byteLength > this._bufferSize && this._expandBuffer(this._stashUsed + e.byteLength);
      let n = new Uint8Array(this._stashBuffer, 0, this._bufferSize);
      n.set(new Uint8Array(e), this._stashUsed), this._stashUsed += e.byteLength;
      let a = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart);
      if (a < this._stashUsed && a > 0) {
        let o = new Uint8Array(this._stashBuffer, a);
        n.set(o, 0);
      }
      this._stashUsed -= a, this._stashByteStart += a;
    }
  }
  _flushStashBuffer(e) {
    if (this._stashUsed > 0) {
      let t = this._stashBuffer.slice(0, this._stashUsed), i = this._dispatchChunks(t, this._stashByteStart), s = t.byteLength - i;
      if (i < t.byteLength)
        if (e)
          S.w(this.TAG, `${s} bytes unconsumed data remain when flush buffer, dropped`);
        else {
          if (i > 0) {
            let n = new Uint8Array(this._stashBuffer, 0, this._bufferSize), a = new Uint8Array(t, i);
            n.set(a, 0), this._stashUsed = a.byteLength, this._stashByteStart += i;
          }
          return 0;
        }
      return this._stashUsed = 0, this._stashByteStart = 0, s;
    }
    return 0;
  }
  _onLoaderComplete(e, t) {
    this._flushStashBuffer(!0), this._onComplete && this._onComplete(this._extraData);
  }
  _onLoaderError(e, t) {
    switch (S.e(this.TAG, `Loader error, code = ${t.code}, msg = ${t.msg}`), this._flushStashBuffer(!1), this._isEarlyEofReconnecting && (this._isEarlyEofReconnecting = !1, e = Ue.UNRECOVERABLE_EARLY_EOF), e) {
      case Ue.EARLY_EOF: {
        if (!this._config.isLive && this._totalLength) {
          let i = this._currentRange.to + 1;
          i < this._totalLength && (S.w(this.TAG, "Connection lost, trying reconnect..."), this._isEarlyEofReconnecting = !0, this._internalSeek(i, !1));
          return;
        }
        e = Ue.UNRECOVERABLE_EARLY_EOF;
        break;
      }
      case Ue.UNRECOVERABLE_EARLY_EOF:
      case Ue.CONNECTING_TIMEOUT:
      case Ue.HTTP_STATUS_CODE_INVALID:
      case Ue.EXCEPTION:
        break;
    }
    if (this._onError)
      this._onError(e, t);
    else
      throw new At("IOException: " + t.msg);
  }
}
const Eb = "application/vnd.apple.mpegurl";
class je {
  static supportVideoDecoder() {
    return !!self.VideoDecoder;
  }
  static supportMSEH264Playback() {
    const e = 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"', t = self.MediaSource && self.MediaSource.isTypeSupported(e), i = self.ManagedMediaSource && self.ManagedMediaSource.isTypeSupported(e);
    return t || i;
  }
  static supportMSEH265Playback() {
    const e = 'video/mp4; codecs="hvc1.1.6.L93.B0"', t = self.MediaSource && self.MediaSource.isTypeSupported(e), i = self.ManagedMediaSource && self.ManagedMediaSource.isTypeSupported(e);
    return t || i;
  }
  static supportNetworkStreamIO() {
    let e = new vc({}, Pr()), t = e.loaderType;
    return e.destroy(), t == "fetch-stream-loader" || t == "xhr-moz-chunked-loader";
  }
  static getNetworkLoaderTypeName() {
    let e = new vc({}, Pr()), t = e.loaderType;
    return e.destroy(), t;
  }
  static supportNativeMediaPlayback(e) {
    je.videoElement == null && (je.videoElement = window.document.createElement("video"));
    let t = je.videoElement.canPlayType(e);
    return t === "probably" || t == "maybe";
  }
  static getFeatureList() {
    let e = {
      nativeHLS: !1,
      msePlayback: !1,
      mseLivePlayback: !1,
      mseH265Playback: !1,
      networkStreamIO: !1,
      networkLoaderName: "",
      nativeMP4H264Playback: !1,
      nativeMP4H265Playback: !1,
      nativeWebmVP8Playback: !1,
      nativeWebmVP9Playback: !1,
      supportVideoDecoder: !1
    };
    return e.nativeHLS = je.supportNativeMediaPlayback(Eb), e.msePlayback = je.supportMSEH264Playback(), e.networkStreamIO = je.supportNetworkStreamIO(), e.networkLoaderName = je.getNetworkLoaderTypeName(), e.mseLivePlayback = e.msePlayback && e.networkStreamIO, e.mseH265Playback = je.supportMSEH265Playback(), e.nativeMP4H264Playback = je.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'), e.nativeMP4H265Playback = je.supportNativeMediaPlayback('video/mp4; codecs="hvc1.1.6.L93.B0"'), e.nativeWebmVP8Playback = je.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'), e.nativeWebmVP9Playback = je.supportNativeMediaPlayback('video/webm; codecs="vp9"'), e.supportVideoDecoder = je.supportVideoDecoder(), e;
  }
}
var Dt = /* @__PURE__ */ ((r) => (r.ERROR = "error", r.SOURCE_OPEN = "source_open", r.UPDATE_END = "update_end", r.BUFFER_FULL = "buffer_full", r.START_STREAMING = "start_streaming", r.END_STREAMING = "end_streaming", r))(Dt || {});
class Sb {
  constructor(e) {
    this.TAG = "MSEController", this._config = e, this._emitter = new ve(), this._config.isLive && this._config.autoCleanupSourceBuffer == null && (this._config.autoCleanupSourceBuffer = !0), this.e = {
      onSourceOpen: this._onSourceOpen.bind(this),
      onSourceEnded: this._onSourceEnded.bind(this),
      onSourceClose: this._onSourceClose.bind(this),
      onStartStreaming: this._onStartStreaming.bind(this),
      onEndStreaming: this._onEndStreaming.bind(this),
      onQualityChange: this._onQualityChange.bind(this),
      onSourceBufferError: this._onSourceBufferError.bind(this),
      onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this)
    }, this._useManagedMediaSource = "ManagedMediaSource" in self && !("MediaSource" in self), this._mediaSource = null, this._mediaSourceObjectURL = null, this._mediaElementProxy = null, this._isBufferFull = !1, this._hasPendingEos = !1, this._requireSetMediaDuration = !1, this._pendingMediaDuration = 0, this._pendingSourceBufferInit = [], this._mimeTypes = {
      video: null,
      audio: null
    }, this._sourceBuffers = {
      video: null,
      audio: null
    }, this._lastInitSegments = {
      video: null,
      audio: null
    }, this._pendingSegments = {
      video: [],
      audio: []
    }, this._pendingRemoveRanges = {
      video: [],
      audio: []
    };
  }
  destroy() {
    this._mediaSource && this.shutdown(), this._mediaSourceObjectURL && this.revokeObjectURL(), this.e = null, this._emitter.removeAllListeners(), this._emitter = null;
  }
  on(e, t) {
    this._emitter.addListener(e, t);
  }
  off(e, t) {
    this._emitter.removeListener(e, t);
  }
  initialize(e) {
    if (this._mediaSource)
      throw new qe("MediaSource has been attached to an HTMLMediaElement!");
    this._useManagedMediaSource && S.v(this.TAG, "Using ManagedMediaSource");
    let t = this._mediaSource = this._useManagedMediaSource ? new self.ManagedMediaSource() : new self.MediaSource();
    t.addEventListener("sourceopen", this.e.onSourceOpen), t.addEventListener("sourceended", this.e.onSourceEnded), t.addEventListener("sourceclose", this.e.onSourceClose), this._useManagedMediaSource && (t.addEventListener("startstreaming", this.e.onStartStreaming), t.addEventListener("endstreaming", this.e.onEndStreaming), t.addEventListener("qualitychange", this.e.onQualityChange)), this._mediaElementProxy = e;
  }
  shutdown() {
    if (this._mediaSource) {
      let e = this._mediaSource;
      for (let t in this._sourceBuffers) {
        let i = this._pendingSegments[t];
        i.splice(0, i.length), this._pendingSegments[t] = null, this._pendingRemoveRanges[t] = null, this._lastInitSegments[t] = null;
        let s = this._sourceBuffers[t];
        if (s) {
          if (e.readyState !== "closed") {
            try {
              e.removeSourceBuffer(s);
            } catch (n) {
              S.e(this.TAG, n.message);
            }
            s.removeEventListener("error", this.e.onSourceBufferError), s.removeEventListener("updateend", this.e.onSourceBufferUpdateEnd);
          }
          this._mimeTypes[t] = null, this._sourceBuffers[t] = null;
        }
      }
      if (e.readyState === "open")
        try {
          e.endOfStream();
        } catch (t) {
          S.e(this.TAG, t.message);
        }
      this._mediaElementProxy = null, e.removeEventListener("sourceopen", this.e.onSourceOpen), e.removeEventListener("sourceended", this.e.onSourceEnded), e.removeEventListener("sourceclose", this.e.onSourceClose), this._useManagedMediaSource && (e.removeEventListener("startstreaming", this.e.onStartStreaming), e.removeEventListener("endstreaming", this.e.onEndStreaming), e.removeEventListener("qualitychange", this.e.onQualityChange)), this._pendingSourceBufferInit = [], this._isBufferFull = !1, this._mediaSource = null;
    }
  }
  isManagedMediaSource() {
    return this._useManagedMediaSource;
  }
  getObject() {
    if (!this._mediaSource)
      throw new qe("MediaSource has not been initialized yet!");
    return this._mediaSource;
  }
  getHandle() {
    if (!this._mediaSource)
      throw new qe("MediaSource has not been initialized yet!");
    return this._mediaSource.handle;
  }
  getObjectURL() {
    if (!this._mediaSource)
      throw new qe("MediaSource has not been initialized yet!");
    return this._mediaSourceObjectURL == null && (this._mediaSourceObjectURL = URL.createObjectURL(this._mediaSource)), this._mediaSourceObjectURL;
  }
  revokeObjectURL() {
    this._mediaSourceObjectURL && (URL.revokeObjectURL(this._mediaSourceObjectURL), this._mediaSourceObjectURL = null);
  }
  appendInitSegment(e, t = void 0) {
    if (!this._mediaSource || this._mediaSource.readyState !== "open" || this._mediaSource.streaming === !1) {
      this._pendingSourceBufferInit.push(e), this._pendingSegments[e.type].push(e);
      return;
    }
    let i = e, s = `${i.container}`;
    i.codec && i.codec.length > 0 && (i.codec === "opus" && ye.safari && (i.codec = "Opus"), s += `;codecs=${i.codec}`);
    let n = !1;
    if (S.v(this.TAG, "Received Initialization Segment, mimeType: " + s), this._lastInitSegments[i.type] = i, s !== this._mimeTypes[i.type]) {
      if (this._mimeTypes[i.type])
        S.v(this.TAG, `Notice: ${i.type} mimeType changed, origin: ${this._mimeTypes[i.type]}, target: ${s}`);
      else {
        n = !0;
        try {
          let a = this._sourceBuffers[i.type] = this._mediaSource.addSourceBuffer(s);
          a.addEventListener("error", this.e.onSourceBufferError), a.addEventListener("updateend", this.e.onSourceBufferUpdateEnd);
        } catch (a) {
          S.e(this.TAG, a.message), this._emitter.emit(Dt.ERROR, { code: a.code, msg: a.message });
          return;
        }
      }
      this._mimeTypes[i.type] = s;
    }
    t || this._pendingSegments[i.type].push(i), n || this._sourceBuffers[i.type] && !this._sourceBuffers[i.type].updating && this._doAppendSegments(), ye.safari && i.container === "audio/mpeg" && i.mediaDuration > 0 && (this._requireSetMediaDuration = !0, this._pendingMediaDuration = i.mediaDuration / 1e3, this._updateMediaSourceDuration());
  }
  appendMediaSegment(e) {
    let t = e;
    this._pendingSegments[t.type].push(t), this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer() && this._doCleanupSourceBuffer();
    let i = this._sourceBuffers[t.type];
    i && !i.updating && !this._hasPendingRemoveRanges() && this._doAppendSegments();
  }
  flush() {
    for (let e in this._sourceBuffers) {
      if (!this._sourceBuffers[e])
        continue;
      let t = this._sourceBuffers[e];
      if (this._mediaSource.readyState === "open")
        try {
          t.abort();
        } catch (s) {
          S.e(this.TAG, s.message);
        }
      let i = this._pendingSegments[e];
      if (i.splice(0, i.length), this._mediaSource.readyState !== "closed") {
        for (let s = 0; s < t.buffered.length; s++) {
          let n = t.buffered.start(s), a = t.buffered.end(s);
          this._pendingRemoveRanges[e].push({ start: n, end: a });
        }
        if (t.updating || this._doRemoveRanges(), ye.safari) {
          let s = this._lastInitSegments[e];
          s && (this._pendingSegments[e].push(s), t.updating || this._doAppendSegments());
        }
      }
    }
  }
  endOfStream() {
    let e = this._mediaSource, t = this._sourceBuffers;
    if (!e || e.readyState !== "open") {
      e && e.readyState === "closed" && this._hasPendingSegments() && (this._hasPendingEos = !0);
      return;
    }
    t.video && t.video.updating || t.audio && t.audio.updating ? this._hasPendingEos = !0 : (this._hasPendingEos = !1, e.endOfStream());
  }
  _needCleanupSourceBuffer() {
    if (!this._config.autoCleanupSourceBuffer)
      return !1;
    let e = this._mediaElementProxy.getCurrentTime();
    for (let t in this._sourceBuffers) {
      let i = this._sourceBuffers[t];
      if (i) {
        let s = i.buffered;
        if (s.length >= 1 && e - s.start(0) >= this._config.autoCleanupMaxBackwardDuration)
          return !0;
      }
    }
    return !1;
  }
  _doCleanupSourceBuffer() {
    let e = this._mediaElementProxy.getCurrentTime();
    for (let t in this._sourceBuffers) {
      let i = this._sourceBuffers[t];
      if (i) {
        let s = i.buffered, n = !1;
        for (let a = 0; a < s.length; a++) {
          let o = s.start(a), c = s.end(a);
          if (o <= e && e < c + 3) {
            if (e - o >= this._config.autoCleanupMaxBackwardDuration) {
              n = !0;
              let l = e - this._config.autoCleanupMinBackwardDuration;
              this._pendingRemoveRanges[t].push({ start: o, end: l });
            }
          } else c < e && (n = !0, this._pendingRemoveRanges[t].push({ start: o, end: c }));
        }
        n && !i.updating && this._doRemoveRanges();
      }
    }
  }
  _updateMediaSourceDuration() {
    let e = this._sourceBuffers;
    if (this._mediaElementProxy.getReadyState() === 0 || this._mediaSource.readyState !== "open" || e.video && e.video.updating || e.audio && e.audio.updating)
      return;
    let t = this._mediaSource.duration, i = this._pendingMediaDuration;
    i > 0 && (isNaN(t) || i > t) && (S.v(this.TAG, `Update MediaSource duration from ${t} to ${i}`), this._mediaSource.duration = i), this._requireSetMediaDuration = !1, this._pendingMediaDuration = 0;
  }
  _doRemoveRanges() {
    for (let e in this._pendingRemoveRanges) {
      if (!this._sourceBuffers[e] || this._sourceBuffers[e].updating)
        continue;
      let t = this._sourceBuffers[e], i = this._pendingRemoveRanges[e];
      for (; i.length && !t.updating; ) {
        let s = i.shift();
        t.remove(s.start, s.end);
      }
    }
  }
  _doAppendSegments() {
    let e = this._pendingSegments;
    for (let t in e)
      if (!(!this._sourceBuffers[t] || this._sourceBuffers[t].updating || this._mediaSource.streaming === !1) && e[t].length > 0) {
        let i = e[t].shift();
        if (typeof i.timestampOffset == "number" && isFinite(i.timestampOffset)) {
          let s = this._sourceBuffers[t].timestampOffset, n = i.timestampOffset / 1e3;
          Math.abs(s - n) > 0.1 && (S.v(this.TAG, `Update MPEG audio timestampOffset from ${s} to ${n}`), this._sourceBuffers[t].timestampOffset = n), delete i.timestampOffset;
        }
        if (!i.data || i.data.byteLength === 0)
          continue;
        try {
          this._sourceBuffers[t].appendBuffer(i.data), this._isBufferFull = !1;
        } catch (s) {
          this._pendingSegments[t].unshift(i), s.code === 22 ? (this._isBufferFull || this._emitter.emit(Dt.BUFFER_FULL), this._isBufferFull = !0) : (S.e(this.TAG, s.message), this._emitter.emit(Dt.ERROR, { code: s.code, msg: s.message }));
        }
      }
  }
  _onSourceOpen() {
    if (S.v(this.TAG, "MediaSource onSourceOpen"), this._mediaSource.removeEventListener("sourceopen", this.e.onSourceOpen), this._pendingSourceBufferInit.length > 0) {
      let e = this._pendingSourceBufferInit;
      for (; e.length; ) {
        let t = e.shift();
        this.appendInitSegment(t, !0);
      }
    }
    this._hasPendingSegments() && this._doAppendSegments(), this._emitter.emit(Dt.SOURCE_OPEN);
  }
  _onStartStreaming() {
    S.v(this.TAG, "ManagedMediaSource onStartStreaming"), this._emitter.emit(Dt.START_STREAMING);
  }
  _onEndStreaming() {
    S.v(this.TAG, "ManagedMediaSource onEndStreaming"), this._emitter.emit(Dt.END_STREAMING);
  }
  _onQualityChange() {
    S.v(this.TAG, "ManagedMediaSource onQualityChange");
  }
  _onSourceEnded() {
    S.v(this.TAG, "MediaSource onSourceEnded");
  }
  _onSourceClose() {
    S.v(this.TAG, "MediaSource onSourceClose"), this._mediaSource && this.e != null && (this._mediaSource.removeEventListener("sourceopen", this.e.onSourceOpen), this._mediaSource.removeEventListener("sourceended", this.e.onSourceEnded), this._mediaSource.removeEventListener("sourceclose", this.e.onSourceClose), this._useManagedMediaSource && (this._mediaSource.removeEventListener("startstreaming", this.e.onStartStreaming), this._mediaSource.removeEventListener("endstreaming", this.e.onEndStreaming), this._mediaSource.removeEventListener("qualitychange", this.e.onQualityChange)));
  }
  _hasPendingSegments() {
    let e = this._pendingSegments;
    return e.video.length > 0 || e.audio.length > 0;
  }
  _hasPendingRemoveRanges() {
    let e = this._pendingRemoveRanges;
    return e.video.length > 0 || e.audio.length > 0;
  }
  _onSourceBufferUpdateEnd() {
    this._requireSetMediaDuration ? this._updateMediaSourceDuration() : this._hasPendingRemoveRanges() ? this._doRemoveRanges() : this._hasPendingSegments() ? this._doAppendSegments() : this._hasPendingEos && this.endOfStream(), this._emitter.emit(Dt.UPDATE_END);
  }
  _onSourceBufferError(e) {
    S.e(this.TAG, `SourceBuffer Error: ${e}`);
  }
}
function qu(r) {
  var e = {};
  function t(s) {
    if (e[s])
      return e[s].exports;
    var n = e[s] = {
      /******/
      i: s,
      /******/
      l: !1,
      /******/
      exports: {}
      /******/
    };
    return r[s].call(n.exports, n, n.exports, t), n.l = !0, n.exports;
  }
  t.m = r, t.c = e, t.i = function(s) {
    return s;
  }, t.d = function(s, n, a) {
    t.o(s, n) || Object.defineProperty(s, n, {
      /******/
      configurable: !1,
      /******/
      enumerable: !0,
      /******/
      get: a
      /******/
    });
  }, t.r = function(s) {
    Object.defineProperty(s, "__esModule", { value: !0 });
  }, t.n = function(s) {
    var n = s && s.__esModule ? (
      /******/
      function() {
        return s.default;
      }
    ) : (
      /******/
      function() {
        return s;
      }
    );
    return t.d(n, "a", n), n;
  }, t.o = function(s, n) {
    return Object.prototype.hasOwnProperty.call(s, n);
  }, t.p = "/", t.oe = function(s) {
    throw console.error(s), s;
  };
  var i = t(t.s = ENTRY_MODULE);
  return i.default || i;
}
var vg = "[\\.|\\-|\\+|\\w|/|@]+", ef = "\\(\\s*(/\\*.*?\\*/)?\\s*.*?(" + vg + ").*?\\)";
function tf(r) {
  return (r + "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
function Tb(r) {
  return !isNaN(1 * r);
}
function bb(r, e, t) {
  var i = {};
  i[t] = [];
  var s = e.toString(), n = s.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);
  if (!n) return i;
  for (var a = n[1], o = new RegExp("(\\\\n|\\W)" + tf(a) + ef, "g"), c; c = o.exec(s); )
    c[3] !== "dll-reference" && i[t].push(c[3]);
  for (o = new RegExp("\\(" + tf(a) + '\\("(dll-reference\\s(' + vg + '))"\\)\\)' + ef, "g"); c = o.exec(s); )
    r[c[2]] || (i[t].push(c[1]), r[c[2]] = __webpack_require__(c[1]).m), i[c[2]] = i[c[2]] || [], i[c[2]].push(c[4]);
  for (var l = Object.keys(i), d = 0; d < l.length; d++)
    for (var h = 0; h < i[l[d]].length; h++)
      Tb(i[l[d]][h]) && (i[l[d]][h] = 1 * i[l[d]][h]);
  return i;
}
function Ab(r) {
  var e = Object.keys(r);
  return e.reduce(function(t, i) {
    return t || r[i].length > 0;
  }, !1);
}
function Cb(r, e) {
  for (var t = {
    main: [e]
  }, i = {
    main: []
  }, s = {
    main: {}
  }; Ab(t); )
    for (var n = Object.keys(t), a = 0; a < n.length; a++) {
      var o = n[a], c = t[o], l = c.pop();
      if (s[o] = s[o] || {}, !(s[o][l] || !r[o][l])) {
        s[o][l] = !0, i[o] = i[o] || [], i[o].push(l);
        for (var d = bb(r, r[o][l], o), h = Object.keys(d), u = 0; u < h.length; u++)
          t[h[u]] = t[h[u]] || [], t[h[u]] = t[h[u]].concat(d[h[u]]);
      }
    }
  return i;
}
function Rb(r, e) {
  e = e || {};
  var t = {
    main: __webpack_modules__
  }, i = e.all ? { main: Object.keys(t.main) } : Cb(t, r), s = "";
  Object.keys(i).filter(function(l) {
    return l !== "main";
  }).forEach(function(l) {
    for (var d = 0; i[l][d]; )
      d++;
    i[l].push(d), t[l][d] = "(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })", s = s + "var " + l + " = (" + qu.toString().replace("ENTRY_MODULE", JSON.stringify(d)) + ")({" + i[l].map(function(h) {
      return "" + JSON.stringify(h) + ": " + t[l][h].toString();
    }).join(",") + `});
`;
  }), s = s + "new ((" + qu.toString().replace("ENTRY_MODULE", JSON.stringify(r)) + ")({" + i.main.map(function(l) {
    return "" + JSON.stringify(l) + ": " + t.main[l].toString();
  }).join(",") + "}))(self);";
  var n = new self.Blob([s], { type: "text/javascript" });
  if (e.bare)
    return n;
  var a = self.URL || self.webkitURL || self.mozURL || self.msURL, o = a.createObjectURL(n), c = new self.Worker(o);
  return c.objectURL = o, c;
}
class We {
  static get forceGlobalTag() {
    return S.FORCE_GLOBAL_TAG;
  }
  static set forceGlobalTag(e) {
    S.FORCE_GLOBAL_TAG = e, We._notifyChange();
  }
  static get globalTag() {
    return S.GLOBAL_TAG;
  }
  static set globalTag(e) {
    S.GLOBAL_TAG = e, We._notifyChange();
  }
  static get enableAll() {
    return S.ENABLE_VERBOSE && S.ENABLE_DEBUG && S.ENABLE_INFO && S.ENABLE_WARN && S.ENABLE_ERROR;
  }
  static set enableAll(e) {
    S.ENABLE_VERBOSE = e, S.ENABLE_DEBUG = e, S.ENABLE_INFO = e, S.ENABLE_WARN = e, S.ENABLE_ERROR = e, We._notifyChange();
  }
  static get enableDebug() {
    return S.ENABLE_DEBUG;
  }
  static set enableDebug(e) {
    S.ENABLE_DEBUG = e, We._notifyChange();
  }
  static get enableVerbose() {
    return S.ENABLE_VERBOSE;
  }
  static set enableVerbose(e) {
    S.ENABLE_VERBOSE = e, We._notifyChange();
  }
  static get enableInfo() {
    return S.ENABLE_INFO;
  }
  static set enableInfo(e) {
    S.ENABLE_INFO = e, We._notifyChange();
  }
  static get enableWarn() {
    return S.ENABLE_WARN;
  }
  static set enableWarn(e) {
    S.ENABLE_WARN = e, We._notifyChange();
  }
  static get enableError() {
    return S.ENABLE_ERROR;
  }
  static set enableError(e) {
    S.ENABLE_ERROR = e, We._notifyChange();
  }
  static getConfig() {
    return {
      globalTag: S.GLOBAL_TAG,
      forceGlobalTag: S.FORCE_GLOBAL_TAG,
      enableVerbose: S.ENABLE_VERBOSE,
      enableDebug: S.ENABLE_DEBUG,
      enableInfo: S.ENABLE_INFO,
      enableWarn: S.ENABLE_WARN,
      enableError: S.ENABLE_ERROR,
      enableCallback: S.ENABLE_CALLBACK
    };
  }
  static applyConfig(e) {
    S.GLOBAL_TAG = e.globalTag, S.FORCE_GLOBAL_TAG = e.forceGlobalTag, S.ENABLE_VERBOSE = e.enableVerbose, S.ENABLE_DEBUG = e.enableDebug, S.ENABLE_INFO = e.enableInfo, S.ENABLE_WARN = e.enableWarn, S.ENABLE_ERROR = e.enableError, S.ENABLE_CALLBACK = e.enableCallback;
  }
  static _notifyChange() {
    let e = We.emitter;
    if (e.listenerCount("change") > 0) {
      let t = We.getConfig();
      e.emit("change", t);
    }
  }
  static registerListener(e) {
    We.emitter.addListener("change", e);
  }
  static removeListener(e) {
    We.emitter.removeListener("change", e);
  }
  static addLogListener(e) {
    S.emitter.addListener("log", e), S.emitter.listenerCount("log") > 0 && (S.ENABLE_CALLBACK = !0, We._notifyChange());
  }
  static removeLogListener(e) {
    S.emitter.removeListener("log", e), S.emitter.listenerCount("log") === 0 && (S.ENABLE_CALLBACK = !1, We._notifyChange());
  }
}
We.emitter = new ve();
class Gs {
  constructor() {
    this.mimeType = null, this.duration = null, this.hasAudio = null, this.hasVideo = null, this.audioCodec = null, this.videoCodec = null, this.audioDataRate = null, this.videoDataRate = null, this.audioSampleRate = null, this.audioChannelCount = null, this.width = null, this.height = null, this.fps = null, this.profile = null, this.level = null, this.refFrames = null, this.chromaFormat = null, this.sarNum = null, this.sarDen = null, this.metadata = null, this.segments = null, this.segmentCount = null, this.hasKeyframesIndex = null, this.keyframesIndex = null;
  }
  isComplete() {
    let e = this.hasAudio === !1 || this.hasAudio === !0 && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null, t = this.hasVideo === !1 || this.hasVideo === !0 && this.videoCodec != null && this.width != null && this.height != null && this.fps != null && this.profile != null && this.level != null && this.refFrames != null && this.chromaFormat != null && this.sarNum != null && this.sarDen != null;
    return this.mimeType != null && e && t;
  }
  isSeekable() {
    return this.hasKeyframesIndex === !0;
  }
  getNearestKeyframe(e) {
    if (this.keyframesIndex == null)
      return null;
    let t = this.keyframesIndex, i = this._search(t.times, e);
    return {
      index: i,
      milliseconds: t.times[i],
      fileposition: t.filepositions[i]
    };
  }
  _search(e, t) {
    let i = 0, s = e.length - 1, n = 0, a = 0, o = s;
    for (t < e[0] && (i = 0, a = o + 1); a <= o; )
      if (n = a + Math.floor((o - a) / 2), n === s || t >= e[n] && t < e[n + 1]) {
        i = n;
        break;
      } else e[n] < t ? a = n + 1 : o = n - 1;
    return i;
  }
}
function i0(r, e, t) {
  let i = r;
  if (e + t < i.length) {
    for (; t--; )
      if ((i[++e] & 192) !== 128)
        return !1;
    return !0;
  } else
    return !1;
}
function sf(r) {
  let e = [], t = r, i = 0, s = r.length;
  for (; i < s; ) {
    if (t[i] < 128) {
      e.push(String.fromCharCode(t[i])), ++i;
      continue;
    } else if (!(t[i] < 192)) {
      if (t[i] < 224) {
        if (i0(t, i, 1)) {
          let n = (t[i] & 31) << 6 | t[i + 1] & 63;
          if (n >= 128) {
            e.push(String.fromCharCode(n & 65535)), i += 2;
            continue;
          }
        }
      } else if (t[i] < 240) {
        if (i0(t, i, 2)) {
          let n = (t[i] & 15) << 12 | (t[i + 1] & 63) << 6 | t[i + 2] & 63;
          if (n >= 2048 && (n & 63488) !== 55296) {
            e.push(String.fromCharCode(n & 65535)), i += 3;
            continue;
          }
        }
      } else if (t[i] < 248 && i0(t, i, 3)) {
        let n = (t[i] & 7) << 18 | (t[i + 1] & 63) << 12 | (t[i + 2] & 63) << 6 | t[i + 3] & 63;
        if (n > 65536 && n < 1114112) {
          n -= 65536, e.push(String.fromCharCode(n >>> 10 | 55296)), e.push(String.fromCharCode(n & 1023 | 56320)), i += 4;
          continue;
        }
      }
    }
    e.push("�"), ++i;
  }
  return e.join("");
}
let _i = function() {
  let r = new ArrayBuffer(2);
  return new DataView(r).setInt16(0, 256, !0), new Int16Array(r)[0] === 256;
}();
class Ut {
  static parseScriptData(e, t, i) {
    let s = {};
    try {
      let n = Ut.parseValue(e, t, i), a = Ut.parseValue(e, t + n.size, i - n.size);
      s[n.data] = a.data;
    } catch (n) {
      S.e("AMF", n.toString());
    }
    return s;
  }
  static parseObject(e, t, i) {
    if (i < 3)
      throw new qe("Data not enough when parse ScriptDataObject");
    let s = Ut.parseString(e, t, i), n = Ut.parseValue(e, t + s.size, i - s.size), a = n.objectEnd;
    return {
      data: {
        name: s.data,
        value: n.data
      },
      size: s.size + n.size,
      objectEnd: a
    };
  }
  static parseVariable(e, t, i) {
    return Ut.parseObject(e, t, i);
  }
  static parseString(e, t, i) {
    if (i < 2)
      throw new qe("Data not enough when parse String");
    let n = new DataView(e, t, i).getUint16(0, !_i), a;
    return n > 0 ? a = sf(new Uint8Array(e, t + 2, n)) : a = "", {
      data: a,
      size: 2 + n
    };
  }
  static parseLongString(e, t, i) {
    if (i < 4)
      throw new qe("Data not enough when parse LongString");
    let n = new DataView(e, t, i).getUint32(0, !_i), a;
    return n > 0 ? a = sf(new Uint8Array(e, t + 4, n)) : a = "", {
      data: a,
      size: 4 + n
    };
  }
  static parseDate(e, t, i) {
    if (i < 10)
      throw new qe("Data size invalid when parse Date");
    let s = new DataView(e, t, i), n = s.getFloat64(0, !_i), a = s.getInt16(8, !_i);
    return n += a * 60 * 1e3, {
      data: new Date(n),
      size: 10
    };
  }
  static parseValue(e, t, i) {
    if (i < 1)
      throw new qe("Data not enough when parse Value");
    let s = new DataView(e, t, i), n = 1, a = s.getUint8(0), o, c = !1;
    try {
      switch (a) {
        case 0:
          o = s.getFloat64(1, !_i), n += 8;
          break;
        case 1: {
          o = !!s.getUint8(1), n += 1;
          break;
        }
        case 2: {
          let l = Ut.parseString(e, t + 1, i - 1);
          o = l.data, n += l.size;
          break;
        }
        case 3: {
          o = {};
          let l = 0;
          for ((s.getUint32(i - 4, !_i) & 16777215) === 9 && (l = 3); n < i - 4; ) {
            let d = Ut.parseObject(e, t + n, i - n - l);
            if (d.objectEnd)
              break;
            o[d.data.name] = d.data.value, n += d.size;
          }
          n <= i - 3 && (s.getUint32(n - 1, !_i) & 16777215) === 9 && (n += 3);
          break;
        }
        case 8: {
          o = {}, n += 4;
          let l = 0;
          for ((s.getUint32(i - 4, !_i) & 16777215) === 9 && (l = 3); n < i - 8; ) {
            let d = Ut.parseVariable(e, t + n, i - n - l);
            if (d.objectEnd)
              break;
            o[d.data.name] = d.data.value, n += d.size;
          }
          n <= i - 3 && (s.getUint32(n - 1, !_i) & 16777215) === 9 && (n += 3);
          break;
        }
        case 9:
          o = void 0, n = 1, c = !0;
          break;
        case 10: {
          o = [];
          let l = s.getUint32(1, !_i);
          n += 4;
          for (let d = 0; d < l; d++) {
            let h = Ut.parseValue(e, t + n, i - n);
            o.push(h.data), n += h.size;
          }
          break;
        }
        case 11: {
          let l = Ut.parseDate(e, t + 1, i - 1);
          o = l.data, n += l.size;
          break;
        }
        case 12: {
          let l = Ut.parseString(e, t + 1, i - 1);
          o = l.data, n += l.size;
          break;
        }
        default:
          n = i, S.w("AMF", "Unsupported AMF value type " + a);
      }
    } catch (l) {
      S.e("AMF", l.toString());
    }
    return {
      data: o,
      size: n,
      objectEnd: c
    };
  }
}
let pi = class {
  constructor(e) {
    this.TAG = "ExpGolomb", this._buffer = e, this._buffer_index = 0, this._total_bytes = e.byteLength, this._total_bits = e.byteLength * 8, this._current_word = 0, this._current_word_bits_left = 0;
  }
  destroy() {
    this._buffer = null;
  }
  _fillCurrentWord() {
    let e = this._total_bytes - this._buffer_index;
    if (e <= 0)
      throw new qe("ExpGolomb: _fillCurrentWord() but no bytes available");
    let t = Math.min(4, e), i = new Uint8Array(4);
    i.set(this._buffer.subarray(this._buffer_index, this._buffer_index + t)), this._current_word = new DataView(i.buffer).getUint32(0, !1), this._buffer_index += t, this._current_word_bits_left = t * 8;
  }
  readBits(e) {
    if (e > 32)
      throw new Yi("ExpGolomb: readBits() bits exceeded max 32bits!");
    if (e <= this._current_word_bits_left) {
      let a = this._current_word >>> 32 - e;
      return this._current_word <<= e, this._current_word_bits_left -= e, a;
    }
    let t = this._current_word_bits_left ? this._current_word : 0;
    t = t >>> 32 - this._current_word_bits_left;
    let i = e - this._current_word_bits_left;
    this._fillCurrentWord();
    let s = Math.min(i, this._current_word_bits_left), n = this._current_word >>> 32 - s;
    return this._current_word <<= s, this._current_word_bits_left -= s, t = t << s | n, t;
  }
  readBool() {
    return this.readBits(1) === 1;
  }
  readByte() {
    return this.readBits(8);
  }
  _skipLeadingZero() {
    let e;
    for (e = 0; e < this._current_word_bits_left; e++)
      if (this._current_word & 2147483648 >>> e)
        return this._current_word <<= e, this._current_word_bits_left -= e, e;
    return this._fillCurrentWord(), e + this._skipLeadingZero();
  }
  readUEG() {
    let e = this._skipLeadingZero();
    return this.readBits(e + 1) - 1;
  }
  readSEG() {
    let e = this.readUEG();
    return e & 1 ? e + 1 >>> 1 : -1 * (e >>> 1);
  }
};
class Ki {
  static _ebsp2rbsp(e) {
    let t = e, i = t.byteLength, s = new Uint8Array(i), n = 0;
    for (let a = 0; a < i; a++)
      a >= 2 && t[a] === 3 && t[a - 1] === 0 && t[a - 2] === 0 || (s[n] = t[a], n++);
    return new Uint8Array(s.buffer, 0, n);
  }
  static parseSPS(e) {
    let t = e.subarray(1, 4), i = "avc1.";
    for (let P = 0; P < 3; P++) {
      let B = t[P].toString(16);
      B.length < 2 && (B = "0" + B), i += B;
    }
    let s = Ki._ebsp2rbsp(e), n = new pi(s);
    n.readByte();
    let a = n.readByte();
    n.readByte();
    let o = n.readByte();
    n.readUEG();
    let c = Ki.getProfileString(a), l = Ki.getLevelString(o), d = 1, h = 420, u = [0, 420, 422, 444], f = 8, p = 8;
    if ((a === 100 || a === 110 || a === 122 || a === 244 || a === 44 || a === 83 || a === 86 || a === 118 || a === 128 || a === 138 || a === 144) && (d = n.readUEG(), d === 3 && n.readBits(1), d <= 3 && (h = u[d]), f = n.readUEG() + 8, p = n.readUEG() + 8, n.readBits(1), n.readBool())) {
      let P = d !== 3 ? 8 : 12;
      for (let B = 0; B < P; B++)
        n.readBool() && (B < 6 ? Ki._skipScalingList(n, 16) : Ki._skipScalingList(n, 64));
    }
    n.readUEG();
    let m = n.readUEG();
    if (m === 0)
      n.readUEG();
    else if (m === 1) {
      n.readBits(1), n.readSEG(), n.readSEG();
      let P = n.readUEG();
      for (let B = 0; B < P; B++)
        n.readSEG();
    }
    let g = n.readUEG();
    n.readBits(1);
    let x = n.readUEG(), _ = n.readUEG(), v = n.readBits(1);
    v === 0 && n.readBits(1), n.readBits(1);
    let E = 0, b = 0, A = 0, C = 0;
    n.readBool() && (E = n.readUEG(), b = n.readUEG(), A = n.readUEG(), C = n.readUEG());
    let L = 1, R = 1, D = 0, M = !0, w = 0, N = 0;
    if (n.readBool()) {
      if (n.readBool()) {
        let P = n.readByte(), B = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], O = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
        P > 0 && P < 16 ? (L = B[P - 1], R = O[P - 1]) : P === 255 && (L = n.readByte() << 8 | n.readByte(), R = n.readByte() << 8 | n.readByte());
      }
      if (n.readBool() && n.readBool(), n.readBool() && (n.readBits(4), n.readBool() && n.readBits(24)), n.readBool() && (n.readUEG(), n.readUEG()), n.readBool()) {
        let P = n.readBits(32), B = n.readBits(32);
        M = n.readBool(), w = B, N = P * 2, D = w / N;
      }
    }
    let G = 1;
    (L !== 1 || R !== 1) && (G = L / R);
    let Z = 0, $ = 0;
    if (d === 0)
      Z = 1, $ = 2 - v;
    else {
      let P = d === 3 ? 1 : 2, B = d === 1 ? 2 : 1;
      Z = P, $ = B * (2 - v);
    }
    let Y = (x + 1) * 16, W = (2 - v) * ((_ + 1) * 16);
    Y -= (E + b) * Z, W -= (A + C) * $;
    let k = Math.ceil(Y * G);
    return n.destroy(), n = null, {
      codec_mimetype: i,
      profile_idc: a,
      level_idc: o,
      profile_string: c,
      // baseline, high, high10, ...
      level_string: l,
      // 3, 3.1, 4, 4.1, 5, 5.1, ...
      chroma_format_idc: d,
      bit_depth: f,
      // 8bit, 10bit, ...
      bit_depth_luma: f,
      bit_depth_chroma: p,
      ref_frames: g,
      chroma_format: h,
      // 4:2:0, 4:2:2, ...
      chroma_format_string: Ki.getChromaFormatString(h),
      frame_rate: {
        fixed: M,
        fps: D,
        fps_den: N,
        fps_num: w
      },
      sar_ratio: {
        width: L,
        height: R
      },
      codec_size: {
        width: Y,
        height: W
      },
      present_size: {
        width: k,
        height: W
      }
    };
  }
  static _skipScalingList(e, t) {
    let i = 8, s = 8, n = 0;
    for (let a = 0; a < t; a++)
      s !== 0 && (n = e.readSEG(), s = (i + n + 256) % 256), i = s === 0 ? i : s;
  }
  static getProfileString(e) {
    switch (e) {
      case 66:
        return "Baseline";
      case 77:
        return "Main";
      case 88:
        return "Extended";
      case 100:
        return "High";
      case 110:
        return "High10";
      case 122:
        return "High422";
      case 244:
        return "High444";
      default:
        return "Unknown";
    }
  }
  static getLevelString(e) {
    return (e / 10).toFixed(1);
  }
  static getChromaFormatString(e) {
    switch (e) {
      case 420:
        return "4:2:0";
      case 422:
        return "4:2:2";
      case 444:
        return "4:4:4";
      default:
        return "Unknown";
    }
  }
}
class di {
  static _ebsp2rbsp(e) {
    let t = e, i = t.byteLength, s = new Uint8Array(i), n = 0;
    for (let a = 0; a < i; a++)
      a >= 2 && t[a] === 3 && t[a - 1] === 0 && t[a - 2] === 0 || (s[n] = t[a], n++);
    return new Uint8Array(s.buffer, 0, n);
  }
  static parseVPS(e) {
    let t = di._ebsp2rbsp(e), i = new pi(t);
    i.readByte(), i.readByte(), i.readBits(4), i.readBits(2), i.readBits(6);
    let s = i.readBits(3), n = i.readBool();
    return {
      num_temporal_layers: s + 1,
      temporal_id_nested: n
    };
  }
  static parseSPS(e) {
    let t = di._ebsp2rbsp(e), i = new pi(t);
    i.readByte(), i.readByte();
    let s = 0, n = 0, a = 0, o = 0;
    i.readBits(4);
    let c = i.readBits(3);
    i.readBool();
    let l = i.readBits(2), d = i.readBool(), h = i.readBits(5), u = i.readByte(), f = i.readByte(), p = i.readByte(), m = i.readByte(), g = i.readByte(), x = i.readByte(), _ = i.readByte(), v = i.readByte(), E = i.readByte(), b = i.readByte(), A = i.readByte(), C = [], I = [];
    for (let ee = 0; ee < c; ee++)
      C.push(i.readBool()), I.push(i.readBool());
    if (c > 0)
      for (let ee = c; ee < 8; ee++)
        i.readBits(2);
    for (let ee = 0; ee < c; ee++)
      C[ee] && (i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte(), i.readByte()), I[ee] && i.readByte();
    i.readUEG();
    let L = i.readUEG();
    L == 3 && i.readBits(1);
    let R = i.readUEG(), D = i.readUEG();
    i.readBool() && (s += i.readUEG(), n += i.readUEG(), a += i.readUEG(), o += i.readUEG());
    let w = i.readUEG(), N = i.readUEG(), H = i.readUEG(), G = i.readBool();
    for (let ee = G ? 0 : c; ee <= c; ee++)
      i.readUEG(), i.readUEG(), i.readUEG();
    if (i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG(), i.readBool() && i.readBool())
      for (let xe = 0; xe < 4; xe++)
        for (let Ee = 0; Ee < (xe === 3 ? 2 : 6); Ee++)
          if (!i.readBool())
            i.readUEG();
          else {
            let Ie = Math.min(64, 1 << 4 + (xe << 1));
            xe > 1 && i.readSEG();
            for (let Ve = 0; Ve < Ie; Ve++)
              i.readSEG();
          }
    i.readBool(), i.readBool(), i.readBool() && (i.readByte(), i.readUEG(), i.readUEG(), i.readBool());
    let Y = i.readUEG(), W = 0;
    for (let ee = 0; ee < Y; ee++) {
      let xe = !1;
      if (ee !== 0 && (xe = i.readBool()), xe) {
        ee === Y && i.readUEG(), i.readBool(), i.readUEG();
        let Ee = 0;
        for (let tt = 0; tt <= W; tt++) {
          let Ie = i.readBool(), Ve = !1;
          Ie || (Ve = i.readBool()), (Ie || Ve) && Ee++;
        }
        W = Ee;
      } else {
        let Ee = i.readUEG(), tt = i.readUEG();
        W = Ee + tt;
        for (let Ie = 0; Ie < Ee; Ie++)
          i.readUEG(), i.readBool();
        for (let Ie = 0; Ie < tt; Ie++)
          i.readUEG(), i.readBool();
      }
    }
    if (i.readBool()) {
      let ee = i.readUEG();
      for (let xe = 0; xe < ee; xe++) {
        for (let Ee = 0; Ee < H + 4; Ee++)
          i.readBits(1);
        i.readBits(1);
      }
    }
    let P = !1, B = 0, O = 1, j = 1, Q = !1, ne = 1, J = 1;
    if (i.readBool(), i.readBool(), i.readBool()) {
      if (i.readBool()) {
        let ke = i.readByte(), Rt = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], Et = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
        ke > 0 && ke <= 16 ? (O = Rt[ke - 1], j = Et[ke - 1]) : ke === 255 && (O = i.readBits(16), j = i.readBits(16));
      }
      if (i.readBool() && i.readBool(), i.readBool() && (i.readBits(3), i.readBool(), i.readBool() && (i.readByte(), i.readByte(), i.readByte())), i.readBool() && (i.readUEG(), i.readUEG()), i.readBool(), i.readBool(), i.readBool(), P = i.readBool(), P && (i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG()), i.readBool() && (ne = i.readBits(32), J = i.readBits(32), i.readBool() && i.readUEG(), i.readBool())) {
        let Et = !1, Fi = !1, lt = !1;
        Et = i.readBool(), Fi = i.readBool(), (Et || Fi) && (lt = i.readBool(), lt && (i.readByte(), i.readBits(5), i.readBool(), i.readBits(5)), i.readBits(4), i.readBits(4), lt && i.readBits(4), i.readBits(5), i.readBits(5), i.readBits(5));
        for (let ei = 0; ei <= c; ei++) {
          let js = i.readBool();
          Q = js;
          let es = !0, Oi = 1;
          js || (es = i.readBool());
          let St = !1;
          if (es ? i.readUEG() : St = i.readBool(), St || (Oi = i.readUEG() + 1), Et) {
            for (let ti = 0; ti < Oi; ti++)
              i.readUEG(), i.readUEG(), lt && (i.readUEG(), i.readUEG());
            i.readBool();
          }
          if (Fi) {
            for (let ti = 0; ti < Oi; ti++)
              i.readUEG(), i.readUEG(), lt && (i.readUEG(), i.readUEG());
            i.readBool();
          }
        }
      }
      i.readBool() && (i.readBool(), i.readBool(), i.readBool(), B = i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG(), i.readUEG());
    }
    i.readBool();
    let Ce = `hvc1.${h}.1.L${A}.B0`, Te = L === 1 || L === 2 ? 2 : 1, Xe = L === 1 ? 2 : 1, be = R - (s + n) * Te, Re = D - (a + o) * Xe, mt = 1;
    return O !== 1 && j !== 1 && (mt = O / j), i.destroy(), i = null, {
      codec_mimetype: Ce,
      profile_string: di.getProfileString(h),
      level_string: di.getLevelString(A),
      profile_idc: h,
      bit_depth: w + 8,
      ref_frames: 1,
      // FIXME!!!
      chroma_format: L,
      chroma_format_string: di.getChromaFormatString(L),
      general_level_idc: A,
      general_profile_space: l,
      general_tier_flag: d,
      general_profile_idc: h,
      general_profile_compatibility_flags_1: u,
      general_profile_compatibility_flags_2: f,
      general_profile_compatibility_flags_3: p,
      general_profile_compatibility_flags_4: m,
      general_constraint_indicator_flags_1: g,
      general_constraint_indicator_flags_2: x,
      general_constraint_indicator_flags_3: _,
      general_constraint_indicator_flags_4: v,
      general_constraint_indicator_flags_5: E,
      general_constraint_indicator_flags_6: b,
      min_spatial_segmentation_idc: B,
      constant_frame_rate: 0,
      chroma_format_idc: L,
      bit_depth_luma_minus8: w,
      bit_depth_chroma_minus8: N,
      frame_rate: {
        fixed: Q,
        fps: J / ne,
        fps_den: ne,
        fps_num: J
      },
      sar_ratio: {
        width: O,
        height: j
      },
      codec_size: {
        width: be,
        height: Re
      },
      present_size: {
        width: be * mt,
        height: Re
      }
    };
  }
  static parsePPS(e) {
    let t = di._ebsp2rbsp(e), i = new pi(t);
    i.readByte(), i.readByte(), i.readUEG(), i.readUEG(), i.readBool(), i.readBool(), i.readBits(3), i.readBool(), i.readBool(), i.readUEG(), i.readUEG(), i.readSEG(), i.readBool(), i.readBool(), i.readBool() && i.readUEG(), i.readSEG(), i.readSEG(), i.readBool(), i.readBool(), i.readBool(), i.readBool();
    let n = i.readBool(), a = i.readBool(), o = 1;
    return a && n ? o = 0 : a ? o = 3 : n && (o = 2), {
      parallelismType: o
    };
  }
  static getChromaFormatString(e) {
    switch (e) {
      case 0:
        return "4:0:0";
      case 1:
        return "4:2:0";
      case 2:
        return "4:2:2";
      case 3:
        return "4:4:4";
      default:
        return "Unknown";
    }
  }
  static getProfileString(e) {
    switch (e) {
      case 1:
        return "Main";
      case 2:
        return "Main10";
      case 3:
        return "MainSP";
      case 4:
        return "Rext";
      case 9:
        return "SCC";
      default:
        return "Unknown";
    }
  }
  static getLevelString(e) {
    return (e / 30).toFixed(1);
  }
}
function rf(r) {
  return r.byteOffset % 2 === 0 && r.byteLength % 2 === 0;
}
function nf(r) {
  return r.byteOffset % 4 === 0 && r.byteLength % 4 === 0;
}
function bd(r, e) {
  for (let t = 0; t < r.length; t++)
    if (r[t] !== e[t])
      return !1;
  return !0;
}
function Ib(r, e) {
  return bd(r, e);
}
function Lb(r, e) {
  let t = new Uint16Array(r.buffer, r.byteOffset, r.byteLength / 2), i = new Uint16Array(e.buffer, e.byteOffset, e.byteLength / 2);
  return bd(t, i);
}
function Db(r, e) {
  let t = new Uint32Array(r.buffer, r.byteOffset, r.byteLength / 4), i = new Uint32Array(e.buffer, e.byteOffset, e.byteLength / 4);
  return bd(t, i);
}
function Wr(r, e) {
  return r.byteLength !== e.byteLength ? !1 : nf(r) && nf(e) ? Db(r, e) : rf(r) && rf(e) ? Lb(r, e) : Ib(r, e);
}
class Xt {
  static parseOBUs(e, t) {
    for (let i = 0; i < e.byteLength; ) {
      let s = i;
      (e[i] & 128) >> 7;
      let n = (e[i] & 120) >> 3, a = (e[i] & 4) !== 0, o = (e[i] & 2) !== 0;
      e[i] & 1, i += 1;
      let c = 0, l = 0;
      a && (i += 1);
      let d = Number.POSITIVE_INFINITY;
      if (o) {
        d = 0;
        for (let h = 0; ; h++) {
          let u = e[i++];
          if (d |= (u & 127) << h * 7, !(u & 128))
            break;
        }
      }
      console.log(n), n === 1 ? t = {
        ...Xt.parseSeuqneceHeader(e.subarray(i, i + d)),
        sequence_header_data: e.subarray(s, i + d)
      } : (n == 3 && t || n == 6 && t) && (t = Xt.parseOBUFrameHeader(e.subarray(i, i + d), c, l, t)), i += d;
    }
    return t;
  }
  static parseSeuqneceHeader(e) {
    let t = new pi(e), i = t.readBits(3);
    t.readBool();
    let s = t.readBool(), n = !0, a = 0, o = 1, c = !1, l, d = [];
    if (s)
      d.push({
        operating_point_idc: 0,
        level: t.readBits(5),
        tier: 0
      });
    else {
      if (t.readBool()) {
        let P = t.readBits(32), B = t.readBits(32), O = t.readBool();
        if (O) {
          let Q = 0;
          for (; t.readBits(1) === 0; )
            Q += 1;
          Q >= 32 || (1 << Q) - 1 + t.readBits(Q);
        }
        o = P, a = B, n = O, t.readBool() && (t.readBits(5), t.readBits(32), l = t.readBits(5), t.readBits(5));
      }
      let W = t.readBool(), k = t.readBits(5);
      for (let P = 0; P <= k; P++) {
        let B = t.readBits(12), O = t.readBits(5), j = O > 7 ? t.readBits(1) : 0;
        d.push({
          operating_point_idc: B,
          level: O,
          tier: j
        }), W && t.readBool() && t.readBits(4);
      }
    }
    let h = 0, { level: u, tier: f } = d[h], p = t.readBits(4), m = t.readBits(4), g = t.readBits(p + 1) + 1, x = t.readBits(m + 1) + 1, _ = !1;
    s || (_ = t.readBool());
    let v, E;
    _ && (t.readBits(4), t.readBits(4));
    let b = 2, A = 2;
    t.readBool(), t.readBool(), t.readBool();
    let C = !1, I = b, L = A, R = 0;
    s || (t.readBool(), t.readBool(), t.readBool(), t.readBool(), C = t.readBool(), C && (t.readBool(), t.readBool()), t.readBool() ? I = b : I = t.readBits(1), I ? t.readBool() ? L = A : L = t.readBits(1) : L = A, C ? R = t.readBits(3) + 1 : R = 0);
    let D = t.readBool();
    t.readBool(), t.readBool();
    let M = t.readBool(), w = 8;
    i === 2 && M ? w = t.readBool() ? 12 : 10 : w = M ? 10 : 8;
    let N = !1;
    i !== 1 && (N = t.readBool()), t.readBool() && (t.readBits(8), t.readBits(8), t.readBits(8));
    let G = 1, Z = 1;
    return N ? (t.readBits(1), G = 1, Z = 1) : (t.readBits(1), i == 0 ? (G = 1, Z = 1) : i == 1 ? (G = 0, Z = 0) : w == 12 ? t.readBits(1) && t.readBits(1) : (G = 1, Z = 0), G && Z && t.readBits(2), t.readBits(1)), t.readBool(), t.destroy(), t = null, {
      codec_mimetype: `av01.${i}.${Xt.getLevelString(u, f)}.${w.toString(10).padStart(2, "0")}`,
      level: u,
      tier: f,
      level_string: Xt.getLevelString(u, f),
      profile_idc: i,
      profile_string: `${i}`,
      bit_depth: w,
      ref_frames: 1,
      // FIXME!!!
      chroma_format: Xt.getChromaFormat(N, G, Z),
      chroma_format_string: Xt.getChromaFormatString(N, G, Z),
      sequence_header: {
        frame_id_numbers_present_flag: _,
        additional_frame_id_length_minus_1: E,
        delta_frame_id_length_minus_2: v,
        reduced_still_picture_header: s,
        decoder_model_info_present_flag: c,
        operating_points: d,
        buffer_removal_time_length_minus_1: l,
        equal_picture_interval: n,
        seq_force_screen_content_tools: I,
        seq_force_integer_mv: L,
        enable_order_hint: C,
        order_hint_bits: R,
        enable_superres: D,
        frame_width_bit: p + 1,
        frame_height_bit: m + 1,
        max_frame_width: g,
        max_frame_height: x
      },
      keyframe: void 0,
      frame_rate: {
        fixed: n,
        fps: a / o,
        fps_den: o,
        fps_num: a
      }
    };
  }
  static parseOBUFrameHeader(e, t, i, s) {
    let { sequence_header: n } = s, a = new pi(e), o = 8, c = 0, l = 2, d = 3, h = 2, u = 2;
    n.max_frame_width, n.max_frame_height;
    let f = 0;
    n.frame_id_numbers_present_flag && (f = n.additional_frame_id_length_minus_1 + n.delta_frame_id_length_minus_2 + 3);
    let p = (1 << o) - 1, m = !1, g = 0, x = !0, _ = !0, v = !1;
    if (!n.reduced_still_picture_header) {
      if (m = a.readBool(), m)
        return s;
      g = a.readBits(2), x = g === l || g === c, _ = a.readBool(), _ && n.decoder_model_info_present_flag && n.equal_picture_interval, _ && a.readBool(), g === d || g === c && _ ? v = !0 : v = a.readBool();
    }
    s.keyframe = x, a.readBool();
    let E = n.seq_force_screen_content_tools;
    n.seq_force_screen_content_tools === h && (E = a.readBits(1)), E && (n.seq_force_integer_mv, n.seq_force_integer_mv == u && a.readBits(1)), n.frame_id_numbers_present_flag && a.readBits(f);
    let b = !1;
    if (g == d ? b = !0 : n.reduced_still_picture_header ? b = !1 : b = a.readBool(), a.readBits(n.order_hint_bits), x || v || a.readBits(3), n.decoder_model_info_present_flag && a.readBool()) {
      for (let I = 0; I <= n.operating_points_cnt_minus_1; I++)
        if (n.operating_points[I].decoder_model_present_for_this_op[I]) {
          let L = n.operating_points[I].operating_point_idc, R = L >> t & 1, D = L >> i + 8 & 1;
          (L === 0 || R && D) && a.readBits(n.buffer_removal_time_length_minus_1 + 1);
        }
    }
    let A = p;
    if (g === d || g == c && _ || (A = a.readBits(8)), (x || A !== p) && v && n.enable_order_hint)
      for (let C = 0; C < o; C++)
        a.readBits(n.order_hint_bits);
    if (x) {
      const C = Xt.frameSizeAndRenderSize(a, b, n);
      s.codec_size = {
        width: C.FrameWidth,
        height: C.FrameHeight
      }, s.present_size = {
        width: C.RenderWidth,
        height: C.RenderHeight
      }, s.sar_ratio = {
        width: C.RenderWidth / C.FrameWidth,
        height: C.RenderHeight / C.FrameHeight
      };
    }
    return a.destroy(), a = null, s;
  }
  static frameSizeAndRenderSize(e, t, i) {
    let s = i.max_frame_width, n = i.max_frame_height;
    t && (s = e.readBits(i.frame_width_bit) + 1, n = e.readBits(i.frame_height_bit) + 1);
    let a = !1;
    i.enable_superres && (a = e.readBool());
    let o = 8;
    a && (o = e.readBits(
      3
      /* SUPERRES_DENOM_BITS */
    ) + 9);
    let c = s;
    s = Math.floor((c * 8 + o / 2) / o);
    let l = e.readBool(), d = c, h = n;
    if (l) {
      let u = e.readBits(16) + 1, f = e.readBits(16) + 1;
      d = e.readBits(u) + 1, h = e.readBits(f) + 1;
    }
    return {
      UpscaledWidth: c,
      FrameWidth: s,
      FrameHeight: n,
      RenderWidth: d,
      RenderHeight: h
    };
  }
  static getLevelString(e, t) {
    return `${e.toString(10).padStart(2, "0")}${t === 0 ? "M" : "H"}`;
  }
  static getChromaFormat(e, t, i) {
    return e ? 0 : t === 0 && i === 0 ? 3 : t === 1 && i === 0 ? 2 : t === 1 && i === 1 ? 1 : Number.NaN;
  }
  static getChromaFormatString(e, t, i) {
    return e ? "4:0:0" : t === 0 && i === 0 ? "4:4:4" : t === 1 && i === 0 ? "4:2:2" : t === 1 && i === 1 ? "4:2:0" : "Unknown";
  }
}
var zt = /* @__PURE__ */ ((r) => (r[r.kUnspecified = 0] = "kUnspecified", r[r.kSliceNonIDR = 1] = "kSliceNonIDR", r[r.kSliceDPA = 2] = "kSliceDPA", r[r.kSliceDPB = 3] = "kSliceDPB", r[r.kSliceDPC = 4] = "kSliceDPC", r[r.kSliceIDR = 5] = "kSliceIDR", r[r.kSliceSEI = 6] = "kSliceSEI", r[r.kSliceSPS = 7] = "kSliceSPS", r[r.kSlicePPS = 8] = "kSlicePPS", r[r.kSliceAUD = 9] = "kSliceAUD", r[r.kEndOfSequence = 10] = "kEndOfSequence", r[r.kEndOfStream = 11] = "kEndOfStream", r[r.kFiller = 12] = "kFiller", r[r.kSPSExt = 13] = "kSPSExt", r[r.kReserved0 = 14] = "kReserved0", r))(zt || {});
class Pb {
  constructor() {
    y(this, "type");
    y(this, "data");
  }
}
class kb {
  constructor(e) {
    y(this, "type");
    y(this, "data");
    let t = e.data.byteLength;
    this.type = e.type, this.data = new Uint8Array(4 + t), new DataView(this.data.buffer).setUint32(0, t), this.data.set(e.data, 4);
  }
}
class wb {
  constructor(e) {
    y(this, "TAG", "H264AnnexBParser");
    y(this, "data_");
    y(this, "current_startcode_offset_", 0);
    y(this, "eof_flag_", !1);
    this.data_ = e, this.current_startcode_offset_ = this.findNextStartCodeOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not find H264 startcode until payload end!");
  }
  findNextStartCodeOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 3 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      let s = i[t + 0] << 24 | i[t + 1] << 16 | i[t + 2] << 8 | i[t + 3], n = i[t + 0] << 16 | i[t + 1] << 8 | i[t + 2];
      if (s === 1 || n === 1)
        return t;
      t++;
    }
  }
  readNextNaluPayload() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_startcode_offset_;
      (e[s] << 24 | e[s + 1] << 16 | e[s + 2] << 8 | e[s + 3]) === 1 ? s += 4 : s += 3;
      let a = e[s] & 31, o = (e[s] & 128) >>> 7, c = this.findNextStartCodeOffset(s);
      if (this.current_startcode_offset_ = c, a >= 14 || o !== 0)
        continue;
      let l = e.subarray(s, c);
      t = new Pb(), t.type = a, t.data = l;
    }
    return t;
  }
}
class Mb {
  // sps, pps: require Nalu without 4 byte length-header
  constructor(e, t, i) {
    y(this, "data");
    let s = 8 + e.byteLength + 1 + 2 + t.byteLength, n = !1;
    e[3] !== 66 && e[3] !== 77 && e[3] !== 88 && (n = !0, s += 4);
    let a = this.data = new Uint8Array(s);
    a[0] = 1, a[1] = e[1], a[2] = e[2], a[3] = e[3], a[4] = 255, a[5] = 225;
    let o = e.byteLength;
    a[6] = o >>> 8, a[7] = o & 255;
    let c = 8;
    a.set(e, 8), c += o, a[c] = 1;
    let l = t.byteLength;
    a[c + 1] = l >>> 8, a[c + 2] = l & 255, a.set(t, c + 3), c += 3 + l, n && (a[c] = 252 | i.chroma_format_idc, a[c + 1] = 248 | i.bit_depth_luma - 8, a[c + 2] = 248 | i.bit_depth_chroma - 8, a[c + 3] = 0, c += 4);
  }
  getData() {
    return this.data;
  }
}
const Ec = new Uint8Array([0, 0, 0, 1]), Bb = Ec.length;
function Fb(r, e) {
  return e === de.H264 && (r >= zt.kSliceNonIDR && r <= zt.kSliceDPC || r === zt.kSliceIDR) || e === de.H265 && (r >= 0 && r <= 9 || r >= 16 && r <= 21);
}
function af(r, e) {
  const t = new Uint8Array(r);
  if (!wm(t, Ec)) return;
  const s = t.length;
  let n, a = 0;
  const o = [];
  let c = 0;
  for (; c !== -1 && c < s; ) {
    if (c = Fb((n == null ? void 0 : n.naluType) ?? -1, e) ? -1 : E2(t, Ec, c), n) {
      const l = t.slice(n.start || 0, c > -1 ? c : t.length);
      n.data = ua(l), o.push(n), a += n.data.byteLength;
    }
    if (c > -1) {
      const l = c + Bb;
      let d = -1;
      e === de.H264 ? d = t[l] & 31 : e === de.H265 && (d = (t[l] & 126) >> 1), n = {
        naluType: d,
        start: l
      }, c = l;
    }
  }
  return {
    length: a,
    units: o
  };
}
const Eg = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
function Ob(r, e) {
  const { channelCount: t, audioSampleRate: i } = e, s = new Uint8Array(r);
  let n = s.length;
  const a = 7, o = new Uint8Array(a);
  let c = n + a;
  o[0] = 255, o[1] = 249;
  let l = Eg.findIndex((h) => h === i);
  return l < 0 && (l = 11), o[2] = 64 | l << 2 | 0, o[3] = t === 2 ? 128 : 64, o[4] = c >> 3 & 255, o[5] = (c & 7) << 5 | 31, o[6] = 252, r = ui(o, s).buffer, r;
}
var li = /* @__PURE__ */ ((r) => (r.NONE = "none", r.MSE = "mse", r.Compatible = "compatible", r))(li || {});
function Nb(r = de.NONE) {
  if (r === de.NONE) return !1;
  const { msePlayback: e, mseH265Playback: t, nativeMP4H265Playback: i, supportVideoDecoder: s } = je.getFeatureList();
  let n = !1, a = !1;
  const o = r === de.H265;
  return S.i("tactics", `videoEncodeType=${r} ${JSON.stringify({ msePlayback: e, mseH265Playback: t, nativeMP4H265Playback: i, supportVideoDecoder: s })} `), s && (a = !o || i), a || (n = e && !o || t && o), n;
}
function Gb(r = de.NONE, e = ae.NONE) {
  let t = Nb(r), i = t ? "mse" : "none", s = "none";
  return !t && r !== de.NONE && (i = "compatible"), t && [ae.AAC, ae.MP3].includes(e) && (s = "mse"), s != "mse" && (s = "compatible"), e === ae.NONE && (s = "none"), {
    videoTactic: i,
    audioTactic: s
  };
}
var Pt = /* @__PURE__ */ ((r) => (r[r.kSliceIDR_W_RADL = 19] = "kSliceIDR_W_RADL", r[r.kSliceIDR_N_LP = 20] = "kSliceIDR_N_LP", r[r.kSliceCRA_NUT = 21] = "kSliceCRA_NUT", r[r.kSliceVPS = 32] = "kSliceVPS", r[r.kSliceSPS = 33] = "kSliceSPS", r[r.kSlicePPS = 34] = "kSlicePPS", r[r.kSliceAUD = 35] = "kSliceAUD", r))(Pt || {});
class Ub {
  constructor() {
    y(this, "type");
    y(this, "data");
  }
}
class Vb {
  constructor(e) {
    y(this, "type");
    y(this, "data");
    let t = e.data.byteLength;
    this.type = e.type, this.data = new Uint8Array(4 + t), new DataView(this.data.buffer).setUint32(0, t), this.data.set(e.data, 4);
  }
}
class Wb {
  constructor(e) {
    y(this, "TAG", "H265AnnexBParser");
    y(this, "data_");
    y(this, "current_startcode_offset_", 0);
    y(this, "eof_flag_", !1);
    this.data_ = e, this.current_startcode_offset_ = this.findNextStartCodeOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not find H265 startcode until payload end!");
  }
  findNextStartCodeOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 3 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      let s = i[t + 0] << 24 | i[t + 1] << 16 | i[t + 2] << 8 | i[t + 3], n = i[t + 0] << 16 | i[t + 1] << 8 | i[t + 2];
      if (s === 1 || n === 1)
        return t;
      t++;
    }
  }
  readNextNaluPayload() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_startcode_offset_;
      (e[s] << 24 | e[s + 1] << 16 | e[s + 2] << 8 | e[s + 3]) === 1 ? s += 4 : s += 3;
      let a = e[s] >> 1 & 63, o = (e[s] & 128) >>> 7, c = this.findNextStartCodeOffset(s);
      if (this.current_startcode_offset_ = c, o !== 0)
        continue;
      let l = e.subarray(s, c);
      t = new Ub(), t.type = a, t.data = l;
    }
    return t;
  }
}
class Hb {
  // sps, pps: require Nalu without 4 byte length-header
  constructor(e, t, i, s) {
    y(this, "data");
    let n = 23 + (5 + e.byteLength) + (5 + t.byteLength) + (5 + i.byteLength), a = this.data = new Uint8Array(n);
    a[0] = 1, a[1] = (s.general_profile_space & 3) << 6 | (s.general_tier_flag ? 1 : 0) << 5 | s.general_profile_idc & 31, a[2] = s.general_profile_compatibility_flags_1, a[3] = s.general_profile_compatibility_flags_2, a[4] = s.general_profile_compatibility_flags_3, a[5] = s.general_profile_compatibility_flags_4, a[6] = s.general_constraint_indicator_flags_1, a[7] = s.general_constraint_indicator_flags_2, a[8] = s.general_constraint_indicator_flags_3, a[9] = s.general_constraint_indicator_flags_4, a[10] = s.general_constraint_indicator_flags_5, a[11] = s.general_constraint_indicator_flags_6, a[12] = s.general_level_idc, a[13] = 240 | (s.min_spatial_segmentation_idc & 3840) >> 8, a[14] = s.min_spatial_segmentation_idc & 255, a[15] = 252 | s.parallelismType & 3, a[16] = 252 | s.chroma_format_idc & 3, a[17] = 248 | s.bit_depth_luma_minus8 & 7, a[18] = 248 | s.bit_depth_chroma_minus8 & 7, a[19] = 0, a[20] = 0, a[21] = (s.constant_frame_rate & 3) << 6 | (s.num_temporal_layers & 7) << 3 | (s.temporal_id_nested ? 1 : 0) << 2 | 3, a[22] = 3, a[23] = 160, a[24] = 0, a[25] = 1, a[26] = (e.byteLength & 65280) >> 8, a[27] = (e.byteLength & 255) >> 0, a.set(e, 28), a[23 + (5 + e.byteLength) + 0] = 161, a[23 + (5 + e.byteLength) + 1] = 0, a[23 + (5 + e.byteLength) + 2] = 1, a[23 + (5 + e.byteLength) + 3] = (t.byteLength & 65280) >> 8, a[23 + (5 + e.byteLength) + 4] = (t.byteLength & 255) >> 0, a.set(t, 23 + (5 + e.byteLength) + 5), a[23 + (5 + e.byteLength + 5 + t.byteLength) + 0] = 162, a[23 + (5 + e.byteLength + 5 + t.byteLength) + 1] = 0, a[23 + (5 + e.byteLength + 5 + t.byteLength) + 2] = 1, a[23 + (5 + e.byteLength + 5 + t.byteLength) + 3] = (i.byteLength & 65280) >> 8, a[23 + (5 + e.byteLength + 5 + t.byteLength) + 4] = (i.byteLength & 255) >> 0, a.set(i, 23 + (5 + e.byteLength + 5 + t.byteLength) + 5);
  }
  getData() {
    return this.data;
  }
}
function Zb(r, e) {
  return r[e] << 24 | r[e + 1] << 16 | r[e + 2] << 8 | r[e + 3];
}
class ja {
  constructor(e, t) {
    this.TAG = S.traceTag("FLVDemuxer", t.traceId), this._config = t, this._onError = null, this._onMediaInfo = null, this._onMetaDataArrived = null, this._onScriptDataArrived = null, this._onTrackMetadata = null, this._onDataAvailable = null, this._dataOffset = e.dataOffset, this._firstParse = !0, this._dispatch = !1, this._hasAudio = e.hasAudioTrack, this._hasVideo = e.hasVideoTrack, this._hasAudioFlagOverrided = !1, this._hasVideoFlagOverrided = !1, this._audioInitialMetadataDispatched = !1, this._videoInitialMetadataDispatched = !1, this._mediaInfo = new Gs(), this._mediaInfo.hasAudio = this._hasAudio, this._mediaInfo.hasVideo = this._hasVideo, this._metadata = null, this._audioMetadata = null, this._videoMetadata = null, this._naluLengthSize = 4, this._timestampBase = 0, this._timescale = 1e3, this._duration = 0, this._durationOverrided = !1, this._referenceFrameRate = {
      fixed: !0,
      fps: 23.976,
      fps_num: 23976,
      fps_den: 1e3
    }, this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48e3], this._mpegSamplingRates = [
      96e3,
      88200,
      64e3,
      48e3,
      44100,
      32e3,
      24e3,
      22050,
      16e3,
      12e3,
      11025,
      8e3,
      7350
    ], this._mpegAudioV10SampleRateTable = [44100, 48e3, 32e3, 0], this._mpegAudioV20SampleRateTable = [22050, 24e3, 16e3, 0], this._mpegAudioV25SampleRateTable = [11025, 12e3, 8e3, 0], this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1], this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1], this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1], this._videoTrack = { type: "video", id: 1, sequenceNumber: 0, samples: [], length: 0 }, this._audioTrack = { type: "audio", id: 2, sequenceNumber: 0, samples: [], length: 0 }, this._littleEndian = function() {
      let i = new ArrayBuffer(2);
      return new DataView(i).setInt16(0, 256, !0), new Int16Array(i)[0] === 256;
    }(), this.onCompatibleVideo = null, this.onCompatibleAudio = null, this.onCustomFlvMessage = null, this._playerTactics = null;
  }
  destroy() {
    this._mediaInfo = null, this._metadata = null, this._audioMetadata = null, this._videoMetadata = null, this._videoTrack = null, this._audioTrack = null, this._onError = null, this._onMediaInfo = null, this._onMetaDataArrived = null, this._onScriptDataArrived = null, this._onTrackMetadata = null, this._onDataAvailable = null, this.onCompatibleVideo = null, this.onCompatibleAudio = null, this.onCustomFlvMessage = null;
  }
  static probe(e) {
    let t = new Uint8Array(e);
    if (t.byteLength < 9)
      return { needMoreData: !0 };
    let i = { match: !1 };
    if (t[0] !== 70 || t[1] !== 76 || t[2] !== 86 || t[3] !== 1)
      return i;
    let s = (t[4] & 4) >>> 2 !== 0, n = (t[4] & 1) !== 0, a = Zb(t, 5);
    return a < 9 ? i : {
      match: !0,
      consumed: a,
      dataOffset: a,
      hasAudioTrack: s,
      hasVideoTrack: n
    };
  }
  bindDataSource(e) {
    return e.onDataArrival = this.parseChunks.bind(this), this;
  }
  // prototype: function(type: string, metadata: any): void
  get onTrackMetadata() {
    return this._onTrackMetadataCallback;
  }
  set onTrackMetadata(e) {
    this._onTrackMetadataCallback = e, this._onTrackMetadata = (t, i) => {
      this._videoSPSConfig = this._videoSPSConfig || {};
      const s = this._videoSPSConfig[t];
      if (s) {
        if (t === "video") {
          if (s.codecWidth === i.codecWidth && s.codec === i.codec)
            return;
        } else if (t === "audio" && s.codec === i.codec)
          return;
      }
      this._videoSPSConfig[t] = { ...i };
      const { video: n, audio: a } = this._videoSPSConfig;
      !n && this._hasVideo || !a && this._hasAudio || (S.d(this.TAG, "onTrackMetadata", n, a), this.onCustomFlvMessage({
        type: "mediaMeta",
        data: {
          video: n,
          audio: a
        }
      }));
    };
  }
  // prototype: function(mediaInfo: MediaInfo): void
  get onMediaInfo() {
    return this._onMediaInfo;
  }
  set onMediaInfo(e) {
    this._onMediaInfo = e;
  }
  get onMetaDataArrived() {
    return this._onMetaDataArrived;
  }
  set onMetaDataArrived(e) {
    this._onMetaDataArrived = e;
  }
  get onScriptDataArrived() {
    return this._onScriptDataArrived;
  }
  set onScriptDataArrived(e) {
    this._onScriptDataArrived = e;
  }
  // prototype: function(type: number, info: string): void
  get onError() {
    return this._onError;
  }
  set onError(e) {
    this._onError = e;
  }
  // prototype: function(videoTrack: any, audioTrack: any): void
  get onDataAvailable() {
    return this._onDataAvailable;
  }
  set onDataAvailable(e) {
    this._onDataAvailable = (t, i) => {
      if (!this._playerTactics) return;
      const { audioTactic: s, videoTactic: n } = this._playerTactics;
      if (s === li.Compatible) {
        const { audio: a } = this._videoSPSConfig, o = za(a.codec) == ae.AAC;
        t.samples.forEach((c) => {
          let { unit: l, dts: d } = c;
          o && (l = Ob(l, a)), this.onCompatibleAudio({ unit: l, dts: d });
        }), t.samples = [], t.length = 0;
      }
      if (n === li.Compatible) {
        const { video: a } = this._videoSPSConfig;
        i.samples.forEach((o) => {
          const { isKeyframe: c, dts: l, units: d } = o;
          if (c) {
            S.d(this.TAG, `received vido keyframe. dts=${l}`);
            let h = !1, u = !1, f = !1;
            const p = a.codec.startsWith("avc"), m = p ? H264NaluType.kSliceSPS : Pt.kSliceSPS, g = p ? H264NaluType.kSlicePPS : Pt.kSlicePPS;
            d.forEach(({ type: x }) => {
              h ? u ? f || (f = !p && x === Pt.kSliceVPS) : u = g : h = x === m;
            }), !u && this._pps && d.unshift({
              type: g,
              data: ua(this._pps)
            }), !h && this._sps && d.unshift({
              type: m,
              data: ua(this._sps)
            }), !f && this._vps && d.unshift({
              type: Pt.kSliceVPS,
              data: ua(this._vps)
            });
          }
          this.onCompatibleVideo(o);
        }), i.samples = [], i.length = 0;
      }
      n == li.MSE && e(t, i);
    };
  }
  setPlayTactics(e) {
    const { video: t, audio: i } = this._videoSPSConfig;
    this._playerTactics = e, S.d(this.TAG, "setPlayTactics", JSON.stringify(e)), t && this._onTrackMetadataCallback("video", t), i && (za(i.codec) === ae.AAC && this._onTrackMetadataCallback("audio", i), this._audioInitialMetadataDispatched = !0, this._isInitialMetadataDispatched() && this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack));
  }
  // timestamp base for output samples, must be in milliseconds
  get timestampBase() {
    return this._timestampBase;
  }
  set timestampBase(e) {
    this._timestampBase = e;
  }
  get overridedDuration() {
    return this._duration;
  }
  // Force-override media duration. Must be in milliseconds, int32
  set overridedDuration(e) {
    this._durationOverrided = !0, this._duration = e, this._mediaInfo.duration = e;
  }
  // Force-override audio track present flag, boolean
  set overridedHasAudio(e) {
    this._hasAudioFlagOverrided = !0, this._hasAudio = e, this._mediaInfo.hasAudio = e;
  }
  // Force-override video track present flag, boolean
  set overridedHasVideo(e) {
    this._hasVideoFlagOverrided = !0, this._hasVideo = e, this._mediaInfo.hasVideo = e;
  }
  resetMediaInfo() {
    this._mediaInfo = new Gs();
  }
  _isInitialMetadataDispatched() {
    return this._hasAudio && this._hasVideo ? this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched : this._hasAudio && !this._hasVideo ? this._audioInitialMetadataDispatched : !this._hasAudio && this._hasVideo ? this._videoInitialMetadataDispatched : !1;
  }
  // function parseChunks(chunk: ArrayBuffer, byteStart: number): number;
  parseChunks(e, t) {
    if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable)
      throw new qe("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");
    let i = 0, s = this._littleEndian;
    if (t === 0)
      if (e.byteLength > 13)
        i = ja.probe(e).dataOffset;
      else
        return 0;
    for (this._firstParse && (this._firstParse = !1, t + i !== this._dataOffset && S.w(this.TAG, "First time parsing but chunk byteStart invalid!"), new DataView(e, i).getUint32(0, !s) !== 0 && S.w(this.TAG, "PrevTagSize0 !== 0 !!!"), i += 4); i < e.byteLength; ) {
      this._dispatch = !0;
      let n = new DataView(e, i);
      if (i + 11 + 4 > e.byteLength)
        break;
      let a = n.getUint8(0), o = n.getUint32(0, !s) & 16777215;
      if (i + 11 + o + 4 > e.byteLength)
        break;
      if (a !== 8 && a !== 9 && a !== 18) {
        S.w(this.TAG, `Unsupported tag type ${a}, skipped`), i += 11 + o + 4;
        continue;
      }
      let c = n.getUint8(4), l = n.getUint8(5), d = n.getUint8(6), h = n.getUint8(7), u = d + (l << 8) + (c << 16) + h * (1 << 24);
      (n.getUint32(7, !s) & 16777215) !== 0 && S.w(this.TAG, "Meet tag which has StreamID != 0!");
      let p = i + 11;
      switch (a) {
        case 8:
          this._parseAudioData(e, p, o, u);
          break;
        case 9:
          this._parseVideoData(e, p, o, u, t + i);
          break;
        case 18:
          this._parseScriptData(e, p, o);
          break;
      }
      let m = n.getUint32(11 + o, !s);
      m !== 11 + o && S.w(this.TAG, `Invalid PrevTagSize ${m}`), i += 11 + o + 4;
    }
    return this._isInitialMetadataDispatched() && this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack), i;
  }
  _parseScriptData(e, t, i) {
    let s = Ut.parseScriptData(e, t, i);
    if (s.hasOwnProperty("onMetaData")) {
      if (s.onMetaData == null || typeof s.onMetaData != "object") {
        S.w(this.TAG, "Invalid onMetaData structure!");
        return;
      }
      this._metadata && S.w(this.TAG, "Found another onMetaData tag!"), this._metadata = s;
      let n = this._metadata.onMetaData;
      if (this._onMetaDataArrived && this._onMetaDataArrived(Object.assign({}, n)), typeof n.hasAudio == "boolean" && this._hasAudioFlagOverrided === !1 && (this._hasAudio = n.hasAudio, this._mediaInfo.hasAudio = this._hasAudio), typeof n.hasVideo == "boolean" && this._hasVideoFlagOverrided === !1 && (this._hasVideo = n.hasVideo, this._mediaInfo.hasVideo = this._hasVideo), typeof n.audiodatarate == "number" && (this._mediaInfo.audioDataRate = n.audiodatarate), typeof n.videodatarate == "number" && (this._mediaInfo.videoDataRate = n.videodatarate), typeof n.width == "number" && (this._mediaInfo.width = n.width), typeof n.height == "number" && (this._mediaInfo.height = n.height), typeof n.duration == "number") {
        if (!this._durationOverrided) {
          let a = Math.floor(n.duration * this._timescale);
          this._duration = a, this._mediaInfo.duration = a;
        }
      } else
        this._mediaInfo.duration = 0;
      if (typeof n.framerate == "number") {
        let a = Math.floor(n.framerate * 1e3);
        if (a > 0) {
          let o = a / 1e3;
          this._referenceFrameRate.fixed = !0, this._referenceFrameRate.fps = o, this._referenceFrameRate.fps_num = a, this._referenceFrameRate.fps_den = 1e3, this._mediaInfo.fps = o;
        }
      }
      if (typeof n.keyframes == "object") {
        this._mediaInfo.hasKeyframesIndex = !0;
        let a = n.keyframes;
        this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(a), n.keyframes = null;
      } else
        this._mediaInfo.hasKeyframesIndex = !1;
      this._dispatch = !1, this._mediaInfo.metadata = n, S.v(this.TAG, "Parsed onMetaData"), this._mediaInfo.isComplete() && this._onMediaInfo(this._mediaInfo);
    }
    Object.keys(s).length > 0 && this._onScriptDataArrived && this._onScriptDataArrived(Object.assign({}, s));
  }
  _parseKeyframesIndex(e) {
    let t = [], i = [];
    for (let s = 1; s < e.times.length; s++) {
      let n = this._timestampBase + Math.floor(e.times[s] * 1e3);
      t.push(n), i.push(e.filepositions[s]);
    }
    return {
      times: t,
      filepositions: i
    };
  }
  _parseAudioData(e, t, i, s) {
    if (i <= 1) {
      S.w(this.TAG, "Flv: Invalid audio packet, missing SoundData payload!");
      return;
    }
    if (this._hasAudioFlagOverrided === !0 && this._hasAudio === !1)
      return;
    this._littleEndian;
    let a = new DataView(e, t, i).getUint8(0), o = a >>> 4;
    if (o === 9) {
      if (i <= 5) {
        S.w(this.TAG, "Flv: Invalid audio packet, missing AudioFourCC in Ehnanced FLV payload!");
        return;
      }
      let p = a & 15, m = String.fromCharCode(...new Uint8Array(e, t, i).slice(1, 5));
      switch (m) {
        case "Opus":
          this._parseOpusAudioPacket(e, t + 5, i - 5, s, p);
          break;
        case "fLaC":
          this._parseFlacAudioPacket(e, t + 5, i - 5, s, p);
          break;
        default:
          this._onError(Fe.CODEC_UNSUPPORTED, "Flv: Unsupported audio codec: " + m);
      }
      return;
    }
    if (o !== 2 && o !== 3 && o !== 7 && o !== 8 && o !== 10) {
      this._onError(Fe.CODEC_UNSUPPORTED, "Flv: Unsupported audio codec idx: " + o);
      return;
    }
    let c = 0, l = (a & 12) >>> 2;
    if (l >= 0 && l <= 4)
      c = this._flvSoundRateTable[l];
    else {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid audio sample rate idx: " + l);
      return;
    }
    let d = (a & 2) >>> 1, h = a & 1, u = this._audioMetadata, f = this._audioTrack;
    if (u || (this._hasAudio === !1 && this._hasAudioFlagOverrided === !1 && (this._hasAudio = !0, this._mediaInfo.hasAudio = !0), u = this._audioMetadata = {}, u.type = "audio", u.id = f.id, u.timescale = this._timescale, u.duration = this._duration, u.audioSampleRate = c, u.channelCount = h === 0 ? 1 : 2), o == 7 || o == 8) {
      u.audioSampleRate = 8e3, u.codec = o == 7 ? "alaw" : "ulaw";
      let p = new Uint8Array(e, t + 1, i - 1), m = new Uint8Array(p.length);
      m.set(p);
      let g = this._timestampBase + s, x = { unit: m.buffer, length: m.length, dts: g, pts: g };
      f.samples.push(x), f.length += m.length, this._lastAudioDTS = g, this._onTrackMetadata("audio", u);
    } else if (o === 12) {
      u.codec = "opus", u.channelCount = 1;
      let p = new Uint8Array(e, t + 1, i - 1), m = new Uint8Array(p.length);
      m.set(p);
      let g = this._timestampBase + s, x = { unit: m.buffer, length: m.length, dts: g, pts: g };
      f.samples.push(x), f.length += m.length, this._lastAudioDTS = g, this._onTrackMetadata("audio", u);
    } else if (o === 10) {
      let p = this._parseAACAudioData(e, t + 1, i - 1);
      if (p == null)
        return;
      if (p.packetType === 0) {
        if (u.config) {
          if (Wr(p.data.config, u.config))
            return;
          S.w(this.TAG, "AudioSpecificConfig has been changed, re-generate initialization segment");
        }
        let m = p.data;
        u.audioSampleRate = m.samplingRate, u.channelCount = m.channelCount, u.codec = m.codec, u.originalCodec = m.originalCodec, u.config = m.config, u.refSampleDuration = 1024 / u.audioSampleRate * u.timescale, S.v(this.TAG, "Parsed AudioSpecificConfig"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._audioInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("audio", u);
        let g = this._mediaInfo;
        g.audioCodec = u.originalCodec, g.audioSampleRate = u.audioSampleRate, g.audioChannelCount = u.channelCount, g.hasVideo ? g.videoCodec != null && (g.mimeType = 'video/x-flv; codecs="' + g.videoCodec + "," + g.audioCodec + '"') : g.mimeType = 'video/x-flv; codecs="' + g.audioCodec + '"', g.isComplete() && this._onMediaInfo(g);
      } else if (p.packetType === 1) {
        let m = this._timestampBase + s, g = { unit: p.data, length: p.data.byteLength, dts: m, pts: m };
        f.samples.push(g), f.length += p.data.length, this._lastAudioDTS = m;
      } else
        S.e(this.TAG, `Flv: Unsupported AAC data type ${p.packetType}`);
    } else if (o === 2) {
      if (!u.codec) {
        let x = this._parseMP3AudioData(e, t + 1, i - 1, !0);
        if (x == null)
          return;
        u.audioSampleRate = x.samplingRate, u.channelCount = x.channelCount, u.codec = x.codec, u.originalCodec = x.originalCodec, u.refSampleDuration = 1152 / u.audioSampleRate * u.timescale, S.v(this.TAG, "Parsed MPEG Audio Frame Header"), this._audioInitialMetadataDispatched = !0, this._onTrackMetadata("audio", u);
        let _ = this._mediaInfo;
        _.audioCodec = u.codec, _.audioSampleRate = u.audioSampleRate, _.audioChannelCount = u.channelCount, _.audioDataRate = x.bitRate, _.hasVideo ? _.videoCodec != null && (_.mimeType = 'video/x-flv; codecs="' + _.videoCodec + "," + _.audioCodec + '"') : _.mimeType = 'video/x-flv; codecs="' + _.audioCodec + '"', _.isComplete() && this._onMediaInfo(_);
      }
      let p = this._parseMP3AudioData(e, t + 1, i - 1, !1);
      if (p == null)
        return;
      let m = this._timestampBase + s, g = { unit: p, length: p.byteLength, dts: m, pts: m };
      f.samples.push(g), f.length += p.length;
    } else if (o === 3) {
      if (!u.codec) {
        u.audioSampleRate = c, u.sampleSize = (d + 1) * 8, u.littleEndian = !0, u.codec = "ipcm", u.originalCodec = "ipcm", this._audioInitialMetadataDispatched = !0, this._onTrackMetadata("audio", u);
        let x = this._mediaInfo;
        x.audioCodec = u.codec, x.audioSampleRate = u.audioSampleRate, x.audioChannelCount = u.channelCount, x.audioDataRate = u.sampleSize * u.audioSampleRate, x.hasVideo ? x.videoCodec != null && (x.mimeType = 'video/x-flv; codecs="' + x.videoCodec + "," + x.audioCodec + '"') : x.mimeType = 'video/x-flv; codecs="' + x.audioCodec + '"', x.isComplete() && this._onMediaInfo(x);
      }
      let p = new Uint8Array(e, t + 1, i - 1), m = this._timestampBase + s, g = { unit: p, length: p.byteLength, dts: m, pts: m };
      f.samples.push(g), f.length += p.length;
    }
  }
  _parseAACAudioData(e, t, i) {
    if (i <= 1) {
      S.w(this.TAG, "Flv: Invalid AAC packet, missing AACPacketType or/and Data!");
      return;
    }
    let s = {}, n = new Uint8Array(e, t, i);
    return s.packetType = n[0], n[0] === 0 ? s.data = this._parseAACAudioSpecificConfig(e, t + 1, i - 1) : s.data = n.subarray(1), s;
  }
  _parseAACAudioSpecificConfig(e, t, i) {
    let s = new Uint8Array(e, t, i), n = null, a = 0, o = 0, c = 0, l = null;
    if (a = o = s[0] >>> 3, c = (s[0] & 7) << 1 | s[1] >>> 7, c < 0 || c >= this._mpegSamplingRates.length) {
      this._onError(Fe.FORMAT_ERROR, "Flv: AAC invalid sampling frequency index!");
      return;
    }
    let d = this._mpegSamplingRates[c], h = (s[1] & 120) >>> 3;
    if (h < 0 || h >= 8) {
      this._onError(Fe.FORMAT_ERROR, "Flv: AAC invalid channel configuration");
      return;
    }
    a === 5 && (l = (s[1] & 7) << 1 | s[2] >>> 7, (s[2] & 124) >>> 2);
    let u = self.navigator.userAgent.toLowerCase();
    return u.indexOf("firefox") !== -1 ? c >= 6 ? (a = 5, n = new Array(4), l = c - 3) : (a = 2, n = new Array(2), l = c) : u.indexOf("android") !== -1 ? (a = 2, n = new Array(2), l = c) : (a = 5, l = c, n = new Array(4), c >= 6 ? l = c - 3 : h === 1 && (a = 2, n = new Array(2), l = c)), n[0] = a << 3, n[0] |= (c & 15) >>> 1, n[1] = (c & 15) << 7, n[1] |= (h & 15) << 3, a === 5 && (n[1] |= (l & 15) >>> 1, n[2] = (l & 1) << 7, n[2] |= 8, n[3] = 0), {
      config: n,
      samplingRate: d,
      channelCount: h,
      codec: "mp4a.40." + a,
      originalCodec: "mp4a.40." + o
    };
  }
  _parseMP3AudioData(e, t, i, s) {
    if (i < 4) {
      S.w(this.TAG, "Flv: Invalid MP3 packet, header missing!");
      return;
    }
    this._littleEndian;
    let n = new Uint8Array(e, t, i), a = null;
    if (s) {
      if (n[0] !== 255)
        return;
      let o = n[1] >>> 3 & 3, c = (n[1] & 6) >> 1, l = (n[2] & 240) >>> 4, d = (n[2] & 12) >>> 2, u = (n[3] >>> 6 & 3) !== 3 ? 2 : 1, f = 0, p = 0, m = "mp3";
      switch (o) {
        case 0:
          f = this._mpegAudioV25SampleRateTable[d];
          break;
        case 2:
          f = this._mpegAudioV20SampleRateTable[d];
          break;
        case 3:
          f = this._mpegAudioV10SampleRateTable[d];
          break;
      }
      switch (c) {
        case 1:
          l < this._mpegAudioL3BitRateTable.length && (p = this._mpegAudioL3BitRateTable[l]);
          break;
        case 2:
          l < this._mpegAudioL2BitRateTable.length && (p = this._mpegAudioL2BitRateTable[l]);
          break;
        case 3:
          l < this._mpegAudioL1BitRateTable.length && (p = this._mpegAudioL1BitRateTable[l]);
          break;
      }
      a = {
        bitRate: p,
        samplingRate: f,
        channelCount: u,
        codec: m,
        originalCodec: m
      };
    } else
      a = n;
    return a;
  }
  _parseOpusAudioPacket(e, t, i, s, n) {
    if (n === 0)
      this._parseOpusSequenceHeader(e, t, i);
    else if (n === 1)
      this._parseOpusAudioData(e, t, i, s);
    else if (n !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid video packet type ${n}`);
      return;
    }
  }
  _parseOpusSequenceHeader(e, t, i) {
    if (i <= 16) {
      S.w(this.TAG, "Flv: Invalid OpusSequenceHeader, lack of data!");
      return;
    }
    let s = this._audioMetadata, n = this._audioTrack;
    s || (this._hasAudio === !1 && this._hasAudioFlagOverrided === !1 && (this._hasAudio = !0, this._mediaInfo.hasAudio = !0), s = this._audioMetadata = {}, s.type = "audio", s.id = n.id, s.timescale = this._timescale, s.duration = this._duration);
    let a = new DataView(e, t, i);
    a.setUint8(8, 0);
    let o = a.getUint8(9);
    a.setUint16(10, a.getUint16(10, !0), !1);
    let c = a.getUint32(12, !0);
    a.setUint32(12, a.getUint32(12, !0), !1);
    let d = {
      config: new Uint8Array(e, t + 8, i - 8),
      channelCount: o,
      samplingFrequence: c,
      codec: "opus",
      originalCodec: "opus"
    };
    if (s.config) {
      if (Wr(d.config, s.config))
        return;
      S.w(this.TAG, "OpusSequenceHeader has been changed, re-generate initialization segment");
    }
    s.audioSampleRate = d.samplingFrequence, s.channelCount = d.channelCount, s.codec = d.codec, s.originalCodec = d.originalCodec, s.config = d.config, s.refSampleDuration = 20, S.v(this.TAG, "Parsed OpusSequenceHeader"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._audioInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("audio", s);
    let h = this._mediaInfo;
    h.audioCodec = s.originalCodec, h.audioSampleRate = s.audioSampleRate, h.audioChannelCount = s.channelCount, h.hasVideo ? h.videoCodec != null && (h.mimeType = 'video/x-flv; codecs="' + h.videoCodec + "," + h.audioCodec + '"') : h.mimeType = 'video/x-flv; codecs="' + h.audioCodec + '"', h.isComplete() && this._onMediaInfo(h);
  }
  _parseOpusAudioData(e, t, i, s) {
    let n = this._audioTrack, a = new Uint8Array(e, t, i), o = this._timestampBase + s, c = { unit: a, length: a.byteLength, dts: o, pts: o };
    n.samples.push(c), n.length += a.length;
  }
  _parseFlacAudioPacket(e, t, i, s, n) {
    if (n === 0)
      this._parseFlacSequenceHeader(e, t, i);
    else if (n === 1)
      this._parseFlacAudioData(e, t, i, s);
    else if (n !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid Flac audio packet type ${n}`);
      return;
    }
  }
  _parseFlacSequenceHeader(e, t, i) {
    let s = this._audioMetadata, n = this._audioTrack;
    s || (this._hasAudio === !1 && this._hasAudioFlagOverrided === !1 && (this._hasAudio = !0, this._mediaInfo.hasAudio = !0), s = this._audioMetadata = {}, s.type = "audio", s.id = n.id, s.timescale = this._timescale, s.duration = this._duration);
    let a = new Uint8Array(e, t + 4, i - 4), o = new pi(a), c = o.readBits(16), l = o.readBits(16), d = l === c ? l : null;
    o.readBits(24), o.readBits(24);
    let h = o.readBits(20), u = o.readBits(3) + 1, f = o.readBits(5) + 1;
    o.destroy();
    let p = new Uint8Array(a.byteLength + 4);
    p.set(a, 4), p[0] = 128, p[1] = a.byteLength >>> 16 & 255, p[2] = a.byteLength >>> 8 & 255, p[3] = a.byteLength >>> 0 & 255;
    let m = {
      config: p,
      channelCount: u,
      samplingFrequence: h,
      sampleSize: f,
      codec: "flac",
      originalCodec: "flac"
    };
    if (s.config) {
      if (Wr(m.config, s.config))
        return;
      S.w(this.TAG, "FlacSequenceHeader has been changed, re-generate initialization segment");
    }
    s.audioSampleRate = m.samplingFrequence, s.channelCount = m.channelCount, s.sampleSize = m.sampleSize, s.codec = m.codec, s.originalCodec = m.originalCodec, s.config = m.config, s.refSampleDuration = d != null ? d * 1e3 / m.samplingFrequence : null, S.v(this.TAG, "Parsed FlacSequenceHeader"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._audioInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("audio", s);
    let g = this._mediaInfo;
    g.audioCodec = s.originalCodec, g.audioSampleRate = s.audioSampleRate, g.audioChannelCount = s.channelCount, g.hasVideo ? g.videoCodec != null && (g.mimeType = 'video/x-flv; codecs="' + g.videoCodec + "," + g.audioCodec + '"') : g.mimeType = 'video/x-flv; codecs="' + g.audioCodec + '"', g.isComplete() && this._onMediaInfo(g);
  }
  _parseFlacAudioData(e, t, i, s) {
    let n = this._audioTrack, a = new Uint8Array(e, t, i), o = this._timestampBase + s, c = { unit: a, length: a.byteLength, dts: o, pts: o };
    n.samples.push(c), n.length += a.length;
  }
  _parseVideoData(e, t, i, s, n) {
    if (i <= 1) {
      S.w(this.TAG, "Flv: Invalid video packet, missing VideoData payload!");
      return;
    }
    if (this._hasVideoFlagOverrided === !0 && this._hasVideo === !1)
      return;
    let a = new Uint8Array(e, t, i)[0], o = (a & 128) !== 0, c = (a & 112) >>> 4;
    if (o) {
      let l = a & 15, d = String.fromCharCode(...new Uint8Array(e, t, i).slice(1, 5));
      if (d === "hvc1")
        this._parseEnhancedHEVCVideoPacket(e, t + 5, i - 5, s, n, c, l);
      else if (d === "av01")
        this._parseEnhancedAV1VideoPacket(e, t + 5, i - 5, s, n, c, l);
      else {
        this._onError(Fe.CODEC_UNSUPPORTED, `Flv: Unsupported codec in video frame: ${d}`);
        return;
      }
    } else {
      let l = a & 15;
      if (l === 7)
        this._parseAVCVideoPacket(e, t + 1, i - 1, s, n, c);
      else if (l === 12)
        this._parseHEVCVideoPacket(e, t + 1, i - 1, s, n, c);
      else {
        this._onError(Fe.CODEC_UNSUPPORTED, `Flv: Unsupported codec in video frame: ${l}`);
        return;
      }
    }
  }
  _parseAVCVideoPacket(e, t, i, s, n, a) {
    if (i < 4) {
      S.w(this.TAG, "Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");
      return;
    }
    let o = this._littleEndian, c = new DataView(e, t, i), l = c.getUint8(0), h = (c.getUint32(0, !o) & 16777215) << 8 >> 8;
    if (l === 0)
      this._parseAVCDecoderConfigurationRecord(e, t + 4, i - 4);
    else if (l === 1)
      this._parseAVCVideoData(e, t + 4, i - 4, s, n, a, h);
    else if (l !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid video packet type ${l}`);
      return;
    }
  }
  _parseHEVCVideoPacket(e, t, i, s, n, a) {
    if (i < 4) {
      S.w(this.TAG, "Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");
      return;
    }
    let o = this._littleEndian, c = new DataView(e, t, i), l = c.getUint8(0), h = (c.getUint32(0, !o) & 16777215) << 8 >> 8;
    if (l === 0)
      this._parseHEVCDecoderConfigurationRecord(e, t + 4, i - 4);
    else if (l === 1)
      this._parseHEVCVideoData(e, t + 4, i - 4, s, n, a, h);
    else if (l !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid video packet type ${l}`);
      return;
    }
  }
  _parseEnhancedHEVCVideoPacket(e, t, i, s, n, a, o) {
    let c = this._littleEndian, l = new DataView(e, t, i);
    if (o === 0)
      this._parseHEVCDecoderConfigurationRecord(e, t, i);
    else if (o === 1) {
      let h = (l.getUint32(0, !c) & 4294967040) >> 8;
      this._parseHEVCVideoData(e, t + 3, i - 3, s, n, a, h);
    } else if (o === 3)
      this._parseHEVCVideoData(e, t, i, s, n, a, 0);
    else if (o !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid video packet type ${o}`);
      return;
    }
  }
  _parseEnhancedAV1VideoPacket(e, t, i, s, n, a, o) {
    if (this._littleEndian, o === 0)
      this._parseAV1CodecConfigurationRecord(e, t, i);
    else if (o === 1)
      this._parseAV1VideoData(e, t, i, s, n, a, 0);
    else if (o === 5) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Not Supported MP2T AV1 video packet type ${o}`);
      return;
    } else if (o !== 2) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Invalid video packet type ${o}`);
      return;
    }
  }
  _parseAVCDecoderConfigurationRecord(e, t, i) {
    if (i < 7) {
      S.w(this.TAG, "Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");
      return;
    }
    let s = this._videoMetadata, n = this._videoTrack, a = this._littleEndian, o = new DataView(e, t, i);
    if (!s)
      this._hasVideo === !1 && this._hasVideoFlagOverrided === !1 && (this._hasVideo = !0, this._mediaInfo.hasVideo = !0), s = this._videoMetadata = {}, s.type = "video", s.id = n.id, s.timescale = this._timescale, s.duration = this._duration;
    else if (typeof s.avcc < "u") {
      let f = new Uint8Array(e, t, i);
      if (Wr(f, s.avcc))
        return;
      S.w(this.TAG, "AVCDecoderConfigurationRecord has been changed, re-generate initialization segment");
    }
    let c = o.getUint8(0), l = o.getUint8(1);
    if (o.getUint8(2), o.getUint8(3), c !== 1 || l === 0) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord");
      return;
    }
    if (this._naluLengthSize = (o.getUint8(4) & 3) + 1, this._naluLengthSize !== 3 && this._naluLengthSize !== 4) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Strange NaluLengthSizeMinusOne: ${this._naluLengthSize - 1}`);
      return;
    }
    let d = o.getUint8(5) & 31;
    if (d === 0) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord: No SPS");
      return;
    } else d > 1 && S.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ${d}`);
    let h = 6;
    for (let f = 0; f < d; f++) {
      let p = o.getUint16(h, !a);
      if (h += 2, p === 0)
        continue;
      let m = new Uint8Array(e, t + h, p);
      h += p;
      let g = Ki.parseSPS(m);
      if (f !== 0)
        continue;
      if (s.codecWidth === g.codec_size.width && s.codecHeight === g.codec_size.height)
        return;
      this._sps = m, s.codecWidth = g.codec_size.width, s.codecHeight = g.codec_size.height, s.presentWidth = g.present_size.width, s.presentHeight = g.present_size.height, s.profile = g.profile_string, s.level = g.level_string, s.bitDepth = g.bit_depth, s.chromaFormat = g.chroma_format, s.sarRatio = g.sar_ratio, s.frameRate = g.frame_rate, (g.frame_rate.fixed === !1 || g.frame_rate.fps_num === 0 || g.frame_rate.fps_den === 0) && (s.frameRate = this._referenceFrameRate);
      let x = s.frameRate.fps_den, _ = s.frameRate.fps_num;
      s.refSampleDuration = s.timescale * (x / _);
      let v = m.subarray(1, 4), E = "avc1.";
      for (let A = 0; A < 3; A++) {
        let C = v[A].toString(16);
        C.length < 2 && (C = "0" + C), E += C;
      }
      s.codec = E;
      let b = this._mediaInfo;
      b.width = s.codecWidth, b.height = s.codecHeight, b.fps = s.frameRate.fps, b.profile = s.profile, b.level = s.level, b.refFrames = g.ref_frames, b.chromaFormat = g.chroma_format_string, b.sarNum = s.sarRatio.width, b.sarDen = s.sarRatio.height, b.videoCodec = E, b.hasAudio ? b.audioCodec != null && (b.mimeType = 'video/x-flv; codecs="' + b.videoCodec + "," + b.audioCodec + '"') : b.mimeType = 'video/x-flv; codecs="' + b.videoCodec + '"', b.isComplete() && this._onMediaInfo(b);
    }
    let u = o.getUint8(h);
    if (u === 0) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord: No PPS");
      return;
    } else u > 1 && S.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ${u}`);
    h++;
    for (let f = 0; f < u; f++) {
      let p = o.getUint16(h, !a);
      h += 2, p !== 0 && (f === 0 && (this._pps = new Uint8Array(e, t + h, p)), h += p);
    }
    s.avcc = new Uint8Array(i), s.avcc.set(new Uint8Array(e, t, i), 0), S.v(this.TAG, "Parsed AVCDecoderConfigurationRecord"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._videoInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("video", s);
  }
  _parseHEVCDecoderConfigurationRecord(e, t, i) {
    if (i < 22) {
      S.w(this.TAG, "Flv: Invalid HEVCDecoderConfigurationRecord, lack of data!");
      return;
    }
    let s = this._videoMetadata, n = this._videoTrack, a = this._littleEndian, o = new DataView(e, t, i);
    if (!s)
      this._hasVideo === !1 && this._hasVideoFlagOverrided === !1 && (this._hasVideo = !0, this._mediaInfo.hasVideo = !0), s = this._videoMetadata = {}, s.type = "video", s.id = n.id, s.timescale = this._timescale, s.duration = this._duration;
    else if (typeof s.hvcc < "u") {
      let u = new Uint8Array(e, t, i);
      if (Wr(u, s.hvcc))
        return;
      S.w(this.TAG, "HEVCDecoderConfigurationRecord has been changed, re-generate initialization segment");
    }
    let c = o.getUint8(0), l = o.getUint8(1) & 31;
    if (c !== 0 && c !== 1 || l === 0) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid HEVCDecoderConfigurationRecord");
      return;
    }
    let d = (o.getUint8(21) & 3) + 1;
    if (d !== 3 && d !== 4) {
      this._onError(Fe.FORMAT_ERROR, `Flv: Strange NaluLengthSizeMinusOne: ${d - 1}`);
      return;
    }
    this._naluLengthSize = d;
    let h = o.getUint8(22);
    for (let u = 0, f = 23; u < h; u++) {
      let p = o.getUint8(f + 0) & 63, m = o.getUint16(f + 1, !a);
      f += 3;
      for (let g = 0; g < m; g++) {
        let x = o.getUint16(f + 0, !a);
        if (g !== 0) {
          f += 2 + x;
          continue;
        }
        if (p === Pt.kSliceSPS) {
          f += 2;
          let _ = this._sps = new Uint8Array(e, t + f, x), v = di.parseSPS(_);
          s.codecWidth = v.codec_size.width, s.codecHeight = v.codec_size.height, s.presentWidth = v.present_size.width, s.presentHeight = v.present_size.height, s.profile = v.profile_string, s.level = v.level_string, s.bitDepth = v.bit_depth, s.chromaFormat = v.chroma_format, s.sarRatio = v.sar_ratio, s.frameRate = v.frame_rate, (v.frame_rate.fixed === !1 || v.frame_rate.fps_num === 0 || v.frame_rate.fps_den === 0) && (s.frameRate = this._referenceFrameRate);
          let E = s.frameRate.fps_den, b = s.frameRate.fps_num;
          s.refSampleDuration = s.timescale * (E / b), s.codec = v.codec_mimetype;
          let A = this._mediaInfo;
          A.width = s.codecWidth, A.height = s.codecHeight, A.fps = s.frameRate.fps, A.profile = s.profile, A.level = s.level, A.refFrames = v.ref_frames, A.chromaFormat = v.chroma_format_string, A.sarNum = s.sarRatio.width, A.sarDen = s.sarRatio.height, A.videoCodec = v.codec_mimetype, A.hasAudio ? A.audioCodec != null && (A.mimeType = 'video/x-flv; codecs="' + A.videoCodec + "," + A.audioCodec + '"') : A.mimeType = 'video/x-flv; codecs="' + A.videoCodec + '"', A.isComplete() && this._onMediaInfo(A), f += x;
        } else
          p === Pt.kSliceVPS ? this._vps = new Uint8Array(e, t + f + 2, x) : p === Pt.kSlicePPS && (this._pps = new Uint8Array(e, t + f + 2, x)), f += 2 + x;
      }
    }
    s.hvcc = new Uint8Array(i), s.hvcc.set(new Uint8Array(e, t, i), 0), S.v(this.TAG, "Parsed HEVCDecoderConfigurationRecord"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._videoInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("video", s);
  }
  _parseAV1CodecConfigurationRecord(e, t, i) {
    if (i < 4) {
      S.w(this.TAG, "Flv: Invalid AV1CodecConfigurationRecord, lack of data!");
      return;
    }
    let s = this._videoMetadata, n = this._videoTrack;
    this._littleEndian;
    let a = new DataView(e, t, i);
    s ? typeof s.av1c < "u" && S.w(this.TAG, "Found another AV1CodecConfigurationRecord!") : (this._hasVideo === !1 && this._hasVideoFlagOverrided === !1 && (this._hasVideo = !0, this._mediaInfo.hasVideo = !0), s = this._videoMetadata = {}, s.type = "video", s.id = n.id, s.timescale = this._timescale, s.duration = this._duration);
    let o = a.getUint8(0) & 127;
    if ((a.getUint8(1) & 224) >> 5, (a.getUint8(1) & 143) >> 0, (a.getUint8(2) & 128) >> 7, o !== 1) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AV1CodecConfigurationRecord");
      return;
    }
    const c = Xt.parseOBUs(new Uint8Array(e, t + 4, i - 4));
    if (c == null) {
      this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AV1CodecConfigurationRecord");
      return;
    }
    s.profile = c.profile_string, s.level = c.level_string, s.bitDepth = c.bit_depth, s.chromaFormat = c.chroma_format, s.frameRate = c.frame_rate, (c.frame_rate.fixed === !1 || c.frame_rate.fps_num === 0 || c.frame_rate.fps_den === 0) && (s.frameRate = this._referenceFrameRate);
    let l = s.frameRate.fps_den, d = s.frameRate.fps_num;
    s.refSampleDuration = s.timescale * (l / d), s.codec = c.codec_mimetype, s.extra = c;
    let h = this._mediaInfo;
    h.fps = s.frameRate.fps, h.profile = s.profile, h.level = s.level, h.refFrames = c.ref_frames, h.chromaFormat = c.chroma_format_string, h.videoCodec = c.codec_mimetype, h.hasAudio ? h.audioCodec != null && (h.mimeType = 'video/x-flv; codecs="' + h.videoCodec + "," + h.audioCodec + '"') : h.mimeType = 'video/x-flv; codecs="' + h.videoCodec + '"', h.isComplete() && this._onMediaInfo(h), s.av1c = new Uint8Array(i), s.av1c.set(new Uint8Array(e, t, i), 0), S.v(this.TAG, "Preparing AV1CodecConfigurationRecord");
  }
  _parseAVCVideoData(e, t, i, s, n, a, o) {
    let c = this._littleEndian, l = new DataView(e, t, i), d = [], h = 0, u = 0;
    const f = this._naluLengthSize;
    let p = this._timestampBase + s, m = a === 1, g = !1;
    for (; u < i; ) {
      if (u + 4 >= i) {
        let _ = !0;
        if (u + 4 == i && (_ = l.getUint32(u, !c) !== 0, g = !_), _) {
          S.w(this.TAG, `Malformed Nalu near timestamp ${p}, offset = ${u}, dataSize = ${i}`);
          break;
        }
      }
      let x = l.getUint32(u, !c);
      if (f === 3 && (x >>>= 8), x > i - f) {
        S.w(this.TAG, `Malformed Nalus near timestamp ${p}, NaluSize > DataSize!`);
        return;
      }
      if (!g) {
        let _;
        const v = new Uint8Array(e, t + u + f, x), E = af(v, de.H264);
        if (E)
          h += E.length, d.push(...E.units), _ = E.units.at(-1);
        else {
          let b = l.getUint8(u + f) & 31, A = new Uint8Array(e, t + u, f + x);
          _ = { type: b, data: A }, d.push(_), h += _.data.byteLength;
        }
        _.type === 5 && (m = !0);
      }
      u += f + x;
    }
    if (d.length || g) {
      let x = this._videoTrack, _ = {
        isStaticFrame: g,
        ipcamTime: this._ipcamTime,
        units: d,
        length: h,
        isKeyframe: m,
        dts: p,
        cts: o,
        pts: p + o
      };
      (m || g) && (_.videoMeta = {
        ...this._videoMetadata,
        codecType: de.H264
      }, _.fileposition = n), x.samples.push(_), x.length += h, this._lastVideoDTS = p;
    }
  }
  _parseHEVCVideoData(e, t, i, s, n, a, o) {
    let c = this._littleEndian, l = new DataView(e, t, i), d = [], h = 0, u = 0;
    const f = this._naluLengthSize;
    let p = this._timestampBase + s, m = a === 1, g = !1;
    for (; u < i; ) {
      if (u + 4 >= i) {
        let _ = !0;
        if (u + 4 == i && (_ = l.getUint32(u, !c) !== 0, g = !_), _) {
          S.w(this.TAG, `Malformed Nalu near timestamp ${p}, offset = ${u}, dataSize = ${i}`);
          break;
        }
      }
      let x = l.getUint32(u, !c);
      if (f === 3 && (x >>>= 8), x > i - f) {
        S.w(this.TAG, `Malformed Nalus near timestamp ${p}, NaluSize > DataSize!`);
        return;
      }
      if (!g) {
        let _;
        const v = new Uint8Array(e, t + u + f, x), E = af(v, de.H265);
        if (E)
          h += E.length, d.push(...E.units), _ = E.units.at(-1);
        else {
          let A = (l.getUint8(u + f) & 126) >> 1, C = new Uint8Array(e, t + u, f + x);
          _ = { type: A, data: C }, d.push(_), h += _.data.byteLength;
        }
        _.type >= 16 && _.type <= 21 && (m = !0);
      }
      u += f + x;
    }
    if (d.length || g) {
      let x = this._videoTrack, _ = {
        isStaticFrame: g,
        ipcamTime: this._ipcamTime,
        units: d,
        length: h,
        isKeyframe: m,
        dts: p,
        cts: o,
        pts: p + o
      };
      (m || g) && (_.videoMeta = {
        ...this._videoMetadata,
        codecType: de.H265
      }, _.fileposition = n), x.samples.push(_), x.length += h, this._lastVideoDTS = p;
    }
  }
  _parseAV1VideoData(e, t, i, s, n, a, o) {
    this._littleEndian;
    let c = [], l = 0, d = 0, h = this._timestampBase + s, u = a === 1;
    if (u) {
      let f = this._videoMetadata;
      const p = Xt.parseOBUs(new Uint8Array(e, t, i), f.extra);
      if (p == null) {
        this._onError(Fe.FORMAT_ERROR, "Flv: Invalid AV1 VideoData");
        return;
      }
      console.log(p), f.codecWidth = p.codec_size.width, f.codecHeight = p.codec_size.height, f.presentWidth = p.present_size.width, f.presentHeight = p.present_size.height, f.sarRatio = p.sar_ratio;
      let m = this._mediaInfo;
      m.width = f.codecWidth, m.height = f.codecHeight, m.sarNum = f.sarRatio.width, m.sarDen = f.sarRatio.height, S.v(this.TAG, "Parsed AV1DecoderConfigurationRecord"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._videoInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("video", f);
    }
    if (l = i, c.push({
      unitType: 0,
      data: new Uint8Array(e, t + d, i)
    }), c.length) {
      let f = this._videoTrack, p = {
        units: c,
        length: l,
        isKeyframe: u,
        dts: h,
        cts: o,
        pts: h + o
      };
      u && (p.fileposition = n), f.samples.push(p), f.length += l;
    }
  }
}
class $b {
  constructor() {
    y(this, "onError");
    y(this, "onMediaInfo");
    y(this, "onMetaDataArrived");
    y(this, "onTrackMetadata");
    y(this, "onDataAvailable");
    y(this, "onTimedID3Metadata");
    y(this, "onPGSSubtitleData");
    y(this, "onSynchronousKLVMetadata");
    y(this, "onAsynchronousKLVMetadata");
    y(this, "onSMPTE2038Metadata");
    y(this, "onSCTE35Metadata");
    y(this, "onPESPrivateData");
    y(this, "onPESPrivateDataDescriptor");
  }
  destroy() {
    this.onError = null, this.onMediaInfo = null, this.onMetaDataArrived = null, this.onTrackMetadata = null, this.onDataAvailable = null, this.onTimedID3Metadata = null, this.onPGSSubtitleData = null, this.onSynchronousKLVMetadata = null, this.onAsynchronousKLVMetadata = null, this.onSMPTE2038Metadata = null, this.onSCTE35Metadata = null, this.onPESPrivateData = null, this.onPESPrivateDataDescriptor = null;
  }
}
class Kb {
  constructor() {
    y(this, "version_number");
    y(this, "network_pid");
    // program_number -> pmt_pid
    y(this, "program_pmt_pid", {});
  }
}
var Ne = /* @__PURE__ */ ((r) => (r[r.kMPEG1Audio = 3] = "kMPEG1Audio", r[r.kMPEG2Audio = 4] = "kMPEG2Audio", r[r.kPESPrivateData = 6] = "kPESPrivateData", r[r.kADTSAAC = 15] = "kADTSAAC", r[r.kLOASAAC = 17] = "kLOASAAC", r[r.kAC3 = 129] = "kAC3", r[r.kEAC3 = 135] = "kEAC3", r[r.kMetadata = 21] = "kMetadata", r[r.kSCTE35 = 134] = "kSCTE35", r[r.kPGS = 144] = "kPGS", r[r.kH264 = 27] = "kH264", r[r.kH265 = 36] = "kH265", r))(Ne || {});
class Xb {
  constructor() {
    y(this, "program_number");
    y(this, "version_number");
    y(this, "pcr_pid");
    // pid -> stream_type
    y(this, "pid_stream_type", {});
    y(this, "common_pids", {
      h264: void 0,
      h265: void 0,
      av1: void 0,
      adts_aac: void 0,
      loas_aac: void 0,
      opus: void 0,
      ac3: void 0,
      eac3: void 0,
      mp3: void 0
    });
    y(this, "pes_private_data_pids", {});
    y(this, "timed_id3_pids", {});
    y(this, "pgs_pids", {});
    y(this, "pgs_langs", {});
    y(this, "synchronous_klv_pids", {});
    y(this, "asynchronous_klv_pids", {});
    y(this, "scte_35_pids", {});
    y(this, "smpte2038_pids", {});
  }
}
class Yb {
  constructor() {
    y(this, "pid");
    y(this, "data");
    y(this, "stream_type");
    y(this, "file_position");
    y(this, "random_access_indicator");
  }
}
class zb {
  constructor() {
    y(this, "pid");
    y(this, "data");
    y(this, "file_position");
    y(this, "random_access_indicator");
  }
}
class of {
  constructor() {
    y(this, "slices", []);
    y(this, "total_length", 0);
    y(this, "expected_length", 0);
    y(this, "file_position", 0);
    y(this, "random_access_indicator");
  }
}
const Qa = [
  96e3,
  88200,
  64e3,
  48e3,
  44100,
  32e3,
  24e3,
  22050,
  16e3,
  12e3,
  11025,
  8e3,
  7350
];
class Sg {
  constructor() {
    y(this, "audio_object_type");
    y(this, "sampling_freq_index");
    y(this, "sampling_frequency");
    y(this, "channel_config");
    y(this, "data");
  }
}
class lf extends Sg {
  constructor() {
    super(...arguments);
    y(this, "other_data_present");
  }
}
class jb {
  constructor(e) {
    y(this, "TAG", "AACADTSParser");
    y(this, "data_");
    y(this, "current_syncword_offset_");
    y(this, "eof_flag_");
    y(this, "has_last_incomplete_data");
    this.data_ = e, this.current_syncword_offset_ = this.findNextSyncwordOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not found ADTS syncword until payload end");
  }
  findNextSyncwordOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 7 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      if ((i[t + 0] << 8 | i[t + 1]) >>> 4 === 4095)
        return t;
      t++;
    }
  }
  readNextAACFrame() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_syncword_offset_, n = (e[s + 1] & 8) >>> 3, a = (e[s + 1] & 6) >>> 1, o = e[s + 1] & 1, c = (e[s + 2] & 192) >>> 6, l = (e[s + 2] & 60) >>> 2, d = (e[s + 2] & 1) << 2 | (e[s + 3] & 192) >>> 6, h = (e[s + 3] & 3) << 11 | e[s + 4] << 3 | (e[s + 5] & 224) >>> 5;
      if (e[s + 6] & 3, s + h > this.data_.byteLength) {
        this.eof_flag_ = !0, this.has_last_incomplete_data = !0;
        break;
      }
      let u = o === 1 ? 7 : 9, f = h - u;
      s += u;
      let p = this.findNextSyncwordOffset(s + f);
      if (this.current_syncword_offset_ = p, n !== 0 && n !== 1 || a !== 0)
        continue;
      let m = e.subarray(s, s + f);
      t = new Sg(), t.audio_object_type = c + 1, t.sampling_freq_index = l, t.sampling_frequency = Qa[l], t.channel_config = d, t.data = m;
    }
    return t;
  }
  hasIncompleteData() {
    return this.has_last_incomplete_data;
  }
  getIncompleteData() {
    return this.has_last_incomplete_data ? this.data_.subarray(this.current_syncword_offset_) : null;
  }
}
class Qb {
  constructor(e) {
    y(this, "TAG", "AACLOASParser");
    y(this, "data_");
    y(this, "current_syncword_offset_");
    y(this, "eof_flag_");
    y(this, "has_last_incomplete_data");
    this.data_ = e, this.current_syncword_offset_ = this.findNextSyncwordOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not found LOAS syncword until payload end");
  }
  findNextSyncwordOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 1 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      if ((i[t + 0] << 3 | i[t + 1] >>> 5) === 695)
        return t;
      t++;
    }
  }
  getLATMValue(e) {
    let t = e.readBits(2), i = 0;
    for (let s = 0; s <= t; s++)
      i = i << 8, i = i | e.readByte();
    return i;
  }
  readNextAACFrame(e) {
    let t = this.data_, i = null;
    for (; i == null && !this.eof_flag_; ) {
      let n = this.current_syncword_offset_, a = (t[n + 1] & 31) << 8 | t[n + 2];
      if (n + 3 + a >= this.data_.byteLength) {
        this.eof_flag_ = !0, this.has_last_incomplete_data = !0;
        break;
      }
      let o = new pi(t.subarray(n + 3, n + 3 + a)), c = o.readBool(), l = null;
      if (c)
        if (e == null) {
          S.w(this.TAG, "StreamMuxConfig Missing"), this.current_syncword_offset_ = this.findNextSyncwordOffset(n + 3 + a), o.destroy();
          continue;
        } else
          l = e;
      else {
        let u = o.readBool();
        if (u && o.readBool()) {
          S.e(this.TAG, "audioMuxVersionA is Not Supported"), o.destroy();
          break;
        }
        if (u && this.getLATMValue(o), !o.readBool()) {
          S.e(this.TAG, "allStreamsSameTimeFraming zero is Not Supported"), o.destroy();
          break;
        }
        if (o.readBits(6) !== 0) {
          S.e(this.TAG, "more than 2 numSubFrames Not Supported"), o.destroy();
          break;
        }
        if (o.readBits(4) !== 0) {
          S.e(this.TAG, "more than 2 numProgram Not Supported"), o.destroy();
          break;
        }
        if (o.readBits(3) !== 0) {
          S.e(this.TAG, "more than 2 numLayer Not Supported"), o.destroy();
          break;
        }
        let _ = u ? this.getLATMValue(o) : 0, v = o.readBits(5);
        _ -= 5;
        let E = o.readBits(4);
        _ -= 4;
        let b = o.readBits(4);
        _ -= 4, o.readBits(3), _ -= 3, _ > 0 && o.readBits(_);
        let A = o.readBits(3);
        if (A === 0)
          o.readByte();
        else {
          S.e(this.TAG, `frameLengthType = ${A}. Only frameLengthType = 0 Supported`), o.destroy();
          break;
        }
        let C = o.readBool();
        if (C)
          if (u)
            this.getLATMValue(o);
          else {
            let L = 0;
            for (; ; ) {
              L = L << 8;
              let R = o.readBool(), D = o.readByte();
              if (L += D, !R)
                break;
            }
            console.log(L);
          }
        o.readBool() && o.readByte(), l = new lf(), l.audio_object_type = v, l.sampling_freq_index = E, l.sampling_frequency = Qa[l.sampling_freq_index], l.channel_config = b, l.other_data_present = C;
      }
      let d = 0;
      for (; ; ) {
        let u = o.readByte();
        if (d += u, u !== 255)
          break;
      }
      let h = new Uint8Array(d);
      for (let u = 0; u < d; u++)
        h[u] = o.readByte();
      i = new lf(), i.audio_object_type = l.audio_object_type, i.sampling_freq_index = l.sampling_freq_index, i.sampling_frequency = Qa[l.sampling_freq_index], i.channel_config = l.channel_config, i.other_data_present = l.other_data_present, i.data = h, this.current_syncword_offset_ = this.findNextSyncwordOffset(n + 3 + a);
    }
    return i;
  }
  hasIncompleteData() {
    return this.has_last_incomplete_data;
  }
  getIncompleteData() {
    return this.has_last_incomplete_data ? this.data_.subarray(this.current_syncword_offset_) : null;
  }
}
class Jb {
  constructor(e) {
    y(this, "config");
    y(this, "sampling_rate");
    y(this, "channel_count");
    y(this, "codec_mimetype");
    y(this, "original_codec_mimetype");
    let t = null, i = e.audio_object_type, s = e.audio_object_type, n = e.sampling_freq_index, a = e.channel_config, o = 0, c = navigator.userAgent.toLowerCase();
    c.indexOf("firefox") !== -1 ? n >= 6 ? (s = 5, t = new Array(4), o = n - 3) : (s = 2, t = new Array(2), o = n) : c.indexOf("android") !== -1 ? (s = 2, t = new Array(2), o = n) : (s = 5, o = n, t = new Array(4), n >= 6 ? o = n - 3 : a === 1 && (s = 2, t = new Array(2), o = n)), t[0] = s << 3, t[0] |= (n & 15) >>> 1, t[1] = (n & 15) << 7, t[1] |= (a & 15) << 3, s === 5 && (t[1] |= (o & 15) >>> 1, t[2] = (o & 1) << 7, t[2] |= 8, t[3] = 0), this.config = t, this.sampling_rate = Qa[n], this.channel_count = a, this.codec_mimetype = "mp4a.40." + s, this.original_codec_mimetype = "mp4a.40." + i;
  }
}
class s0 {
  constructor() {
    y(this, "pid");
    y(this, "stream_id");
    y(this, "pts");
    y(this, "dts");
    y(this, "nearest_pts");
    y(this, "data");
    y(this, "len");
  }
}
class qb {
  constructor() {
    y(this, "pid");
    y(this, "stream_type");
    y(this, "descriptor");
  }
}
const Ad = (r) => {
  const e = r.readBool();
  if (e) {
    r.readBits(6);
    const t = r.readBits(31) * 4 + r.readBits(2);
    return {
      time_specified_flag: e,
      pts_time: t
    };
  } else
    return r.readBits(7), { time_specified_flag: e };
}, Tg = (r) => {
  const e = r.readBool();
  r.readBits(6);
  const t = r.readBits(31) * 4 + r.readBits(2);
  return {
    auto_return: e,
    duration: t
  };
}, eA = (r, e) => {
  const t = e.readBits(8);
  if (r)
    return { component_tag: t };
  const i = Ad(e);
  return {
    component_tag: t,
    splice_time: i
  };
}, tA = (r) => {
  const e = r.readBits(8), t = r.readBits(32);
  return {
    component_tag: e,
    utc_splice_time: t
  };
}, iA = (r) => {
  const e = r.readBits(32), t = r.readBool();
  r.readBits(7);
  const i = {
    splice_event_id: e,
    splice_event_cancel_indicator: t
  };
  if (t)
    return i;
  if (i.out_of_network_indicator = r.readBool(), i.program_splice_flag = r.readBool(), i.duration_flag = r.readBool(), r.readBits(5), i.program_splice_flag)
    i.utc_splice_time = r.readBits(32);
  else {
    i.component_count = r.readBits(8), i.components = [];
    for (let s = 0; s < i.component_count; s++)
      i.components.push(tA(r));
  }
  return i.duration_flag && (i.break_duration = Tg(r)), i.unique_program_id = r.readBits(16), i.avail_num = r.readBits(8), i.avails_expected = r.readBits(8), i;
}, sA = () => ({}), rA = (r) => {
  const e = r.readBits(8), t = [];
  for (let i = 0; i < e; i++)
    t.push(iA(r));
  return {
    splice_count: e,
    events: t
  };
}, nA = (r) => {
  const e = r.readBits(32), t = r.readBool();
  r.readBits(7);
  const i = {
    splice_event_id: e,
    splice_event_cancel_indicator: t
  };
  if (t)
    return i;
  if (i.out_of_network_indicator = r.readBool(), i.program_splice_flag = r.readBool(), i.duration_flag = r.readBool(), i.splice_immediate_flag = r.readBool(), r.readBits(4), i.program_splice_flag && !i.splice_immediate_flag && (i.splice_time = Ad(r)), !i.program_splice_flag) {
    i.component_count = r.readBits(8), i.components = [];
    for (let s = 0; s < i.component_count; s++)
      i.components.push(eA(i.splice_immediate_flag, r));
  }
  return i.duration_flag && (i.break_duration = Tg(r)), i.unique_program_id = r.readBits(16), i.avail_num = r.readBits(8), i.avails_expected = r.readBits(8), i;
}, aA = (r) => ({
  splice_time: Ad(r)
}), oA = () => ({}), lA = (r, e) => {
  const t = String.fromCharCode(e.readBits(8), e.readBits(8), e.readBits(8), e.readBits(8)), i = new Uint8Array(r - 4);
  for (let s = 0; s < r - 4; s++)
    i[s] = e.readBits(8);
  return {
    identifier: t,
    private_data: i.buffer
  };
}, cA = (r, e, t, i) => {
  const s = i.readBits(32);
  return {
    descriptor_tag: r,
    descriptor_length: e,
    identifier: t,
    provider_avail_id: s
  };
}, dA = (r, e, t, i) => {
  const s = i.readBits(8), n = i.readBits(3);
  i.readBits(5);
  let a = "";
  for (let o = 0; o < n; o++)
    a += String.fromCharCode(i.readBits(8));
  return {
    descriptor_tag: r,
    descriptor_length: e,
    identifier: t,
    preroll: s,
    dtmf_count: n,
    DTMF_char: a
  };
}, hA = (r) => {
  const e = r.readBits(8);
  r.readBits(7);
  const t = r.readBits(31) * 4 + r.readBits(2);
  return {
    component_tag: e,
    pts_offset: t
  };
}, uA = (r, e, t, i) => {
  const s = i.readBits(32), n = i.readBool();
  i.readBits(7);
  const a = {
    descriptor_tag: r,
    descriptor_length: e,
    identifier: t,
    segmentation_event_id: s,
    segmentation_event_cancel_indicator: n
  };
  if (n)
    return a;
  if (a.program_segmentation_flag = i.readBool(), a.segmentation_duration_flag = i.readBool(), a.delivery_not_restricted_flag = i.readBool(), a.delivery_not_restricted_flag ? i.readBits(5) : (a.web_delivery_allowed_flag = i.readBool(), a.no_regional_blackout_flag = i.readBool(), a.archive_allowed_flag = i.readBool(), a.device_restrictions = i.readBits(2)), !a.program_segmentation_flag) {
    a.component_count = i.readBits(8), a.components = [];
    for (let o = 0; o < a.component_count; o++)
      a.components.push(hA(i));
  }
  a.segmentation_duration_flag && (a.segmentation_duration = i.readBits(40)), a.segmentation_upid_type = i.readBits(8), a.segmentation_upid_length = i.readBits(8);
  {
    const o = new Uint8Array(a.segmentation_upid_length);
    for (let c = 0; c < a.segmentation_upid_length; c++)
      o[c] = i.readBits(8);
    a.segmentation_upid = o.buffer;
  }
  return a.segmentation_type_id = i.readBits(8), a.segment_num = i.readBits(8), a.segments_expected = i.readBits(8), (a.segmentation_type_id === 52 || a.segmentation_type_id === 54 || a.segmentation_type_id === 56 || a.segmentation_type_id === 58) && (a.sub_segment_num = i.readBits(8), a.sub_segments_expected = i.readBits(8)), a;
}, fA = (r, e, t, i) => {
  const s = i.readBits(48), n = i.readBits(32), a = i.readBits(16);
  return {
    descriptor_tag: r,
    descriptor_length: e,
    identifier: t,
    TAI_seconds: s,
    TAI_ns: n,
    UTC_offset: a
  };
}, pA = (r) => {
  const e = r.readBits(8), t = String.fromCharCode(r.readBits(8), r.readBits(8), r.readBits(8)), i = r.readBits(3), s = r.readBits(4), n = r.readBool();
  return {
    component_tag: e,
    ISO_code: t,
    Bit_Stream_Mode: i,
    Num_Channels: s,
    Full_Srvc_Audio: n
  };
}, mA = (r, e, t, i) => {
  const s = i.readBits(4), n = [];
  for (let a = 0; a < s; a++)
    n.push(pA(i));
  return {
    descriptor_tag: r,
    descriptor_length: e,
    identifier: t,
    audio_count: s,
    components: n
  };
}, gA = (r) => {
  const e = new pi(r), t = e.readBits(8), i = e.readBool(), s = e.readBool();
  e.readBits(2);
  const n = e.readBits(12), a = e.readBits(8), o = e.readBool(), c = e.readBits(6), l = e.readBits(31) * 4 + e.readBits(2), d = e.readBits(8), h = e.readBits(12), u = e.readBits(12), f = e.readBits(8);
  let p = null;
  f === 0 ? p = sA() : f === 4 ? p = rA(e) : f === 5 ? p = nA(e) : f === 6 ? p = aA(e) : f === 7 ? p = oA() : f === 255 ? p = lA(u, e) : e.readBits(u * 8);
  const m = [], g = e.readBits(16);
  for (let E = 0; E < g; ) {
    const b = e.readBits(8), A = e.readBits(8), C = String.fromCharCode(e.readBits(8), e.readBits(8), e.readBits(8), e.readBits(8));
    b === 0 ? m.push(cA(b, A, C, e)) : b === 1 ? m.push(dA(b, A, C, e)) : b === 2 ? m.push(uA(b, A, C, e)) : b === 3 ? m.push(fA(b, A, C, e)) : b === 4 ? m.push(mA(b, A, C, e)) : e.readBits((A - 4) * 8), E += 2 + A;
  }
  const x = o ? e.readBits(32) : void 0, _ = e.readBits(32), v = {
    table_id: t,
    section_syntax_indicator: i,
    private_indicator: s,
    section_length: n,
    protocol_version: a,
    encrypted_packet: o,
    encryption_algorithm: c,
    pts_adjustment: l,
    cw_index: d,
    tier: h,
    splice_command_length: u,
    splice_command_type: f,
    splice_command: p,
    descriptor_loop_length: g,
    splice_descriptors: m,
    E_CRC32: x,
    CRC32: _
  };
  if (f === 5) {
    const E = p;
    if (E.splice_event_cancel_indicator)
      return {
        splice_command_type: f,
        detail: v,
        data: r
      };
    if (E.program_splice_flag && !E.splice_immediate_flag) {
      const b = E.duration_flag ? E.break_duration.auto_return : void 0, A = E.duration_flag ? E.break_duration.duration / 90 : void 0;
      return E.splice_time.time_specified_flag ? {
        splice_command_type: f,
        pts: (l + E.splice_time.pts_time) % 2 ** 33,
        auto_return: b,
        duraiton: A,
        detail: v,
        data: r
      } : {
        splice_command_type: f,
        auto_return: b,
        duraiton: A,
        detail: v,
        data: r
      };
    } else {
      const b = E.duration_flag ? E.break_duration.auto_return : void 0, A = E.duration_flag ? E.break_duration.duration / 90 : void 0;
      return {
        splice_command_type: f,
        auto_return: b,
        duraiton: A,
        detail: v,
        data: r
      };
    }
  } else if (f === 6) {
    const E = p;
    return E.splice_time.time_specified_flag ? {
      splice_command_type: f,
      pts: (l + E.splice_time.pts_time) % 2 ** 33,
      detail: v,
      data: r
    } : {
      splice_command_type: f,
      detail: v,
      data: r
    };
  } else
    return {
      splice_command_type: f,
      detail: v,
      data: r
    };
};
class _A {
  constructor() {
    y(this, "pid");
    y(this, "stream_id");
    y(this, "pts");
    y(this, "dts");
    y(this, "nearest_pts");
    y(this, "ancillaries");
    y(this, "data");
    y(this, "len");
  }
}
const yA = (r) => {
  let e = new pi(r), t = 0, i = [];
  for (; ; ) {
    let s = e.readBits(6);
    if (t += 6, s !== 0)
      break;
    let n = e.readBool();
    t += 1;
    let a = e.readBits(11);
    t += 11;
    let o = e.readBits(12);
    t += 12;
    let c = e.readBits(10) & 255;
    t += 10;
    let l = e.readBits(10) & 255;
    t += 10;
    let d = e.readBits(10) & 255;
    t += 10;
    let h = new Uint8Array(d);
    for (let p = 0; p < d; p++) {
      let m = e.readBits(10) & 255;
      t += 10, h[p] = m;
    }
    e.readBits(10), t += 10;
    let u = "User Defined", f = {};
    c === 65 ? l === 7 && (u = "SCTE-104") : c === 95 ? l === 220 ? u = "ARIB STD-B37 (1SEG)" : l === 221 ? u = "ARIB STD-B37 (ANALOG)" : l === 222 ? u = "ARIB STD-B37 (SD)" : l === 223 && (u = "ARIB STD-B37 (HD)") : c === 97 && (l === 1 ? u = "EIA-708" : l === 2 && (u = "EIA-608")), i.push({
      yc_indicator: n,
      line_number: a,
      horizontal_offset: o,
      did: c,
      sdid: l,
      user_data: h,
      description: u,
      information: f
    }), e.readBits(8 - (t - Math.floor(t / 8)) % 8), t += (8 - (t - Math.floor(t / 8))) % 8;
  }
  return e.destroy(), e = null, i;
};
class xA {
  constructor() {
    y(this, "object_type");
    y(this, "sample_rate");
    y(this, "channel_count");
    y(this, "data");
  }
}
class vA {
  constructor() {
    y(this, "sampling_frequency");
    y(this, "sampling_rate_code");
    y(this, "bit_stream_identification");
    y(this, "bit_stream_mode");
    y(this, "low_frequency_effects_channel_on");
    y(this, "frame_size_code");
    y(this, "channel_count");
    y(this, "channel_mode");
    y(this, "data");
  }
}
const EA = [
  [
    64,
    64,
    80,
    80,
    96,
    96,
    112,
    112,
    128,
    128,
    160,
    160,
    192,
    192,
    224,
    224,
    256,
    256,
    320,
    320,
    384,
    384,
    448,
    448,
    512,
    512,
    640,
    640,
    768,
    768,
    896,
    896,
    1024,
    1024,
    1152,
    1152,
    1280,
    1280
  ],
  [
    69,
    70,
    87,
    88,
    104,
    105,
    121,
    122,
    139,
    140,
    174,
    175,
    208,
    209,
    243,
    244,
    278,
    279,
    348,
    349,
    417,
    418,
    487,
    488,
    557,
    558,
    696,
    697,
    835,
    836,
    975,
    976,
    1114,
    1115,
    1253,
    1254,
    1393,
    1394
  ],
  [
    96,
    96,
    120,
    120,
    144,
    144,
    168,
    168,
    192,
    192,
    240,
    240,
    288,
    288,
    336,
    336,
    384,
    384,
    480,
    480,
    576,
    576,
    672,
    672,
    768,
    768,
    960,
    960,
    1152,
    1152,
    1344,
    1344,
    1536,
    1536,
    1728,
    1728,
    1920,
    1920
  ]
];
class SA {
  constructor(e) {
    y(this, "TAG", "AC3Parser");
    y(this, "data_");
    y(this, "current_syncword_offset_");
    y(this, "eof_flag_");
    y(this, "has_last_incomplete_data");
    this.data_ = e, this.current_syncword_offset_ = this.findNextSyncwordOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not found AC3 syncword until payload end");
  }
  findNextSyncwordOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 7 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      if ((i[t + 0] << 8 | i[t + 1] << 0) === 2935)
        return t;
      t++;
    }
  }
  readNextAC3Frame() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_syncword_offset_, n = e[s + 4] >> 6, a = [48e3, 44200, 33e3][n], o = e[s + 4] & 63, c = EA[n][o] * 2;
      if (isNaN(c) || s + c > this.data_.byteLength) {
        this.eof_flag_ = !0, this.has_last_incomplete_data = !0;
        break;
      }
      let l = this.findNextSyncwordOffset(s + c);
      this.current_syncword_offset_ = l;
      let d = e[s + 5] >> 3, h = e[s + 5] & 7, u = e[s + 6] >> 5, f = 0;
      u & 1 && u !== 1 && (f += 2), u & 4 && (f += 2), u === 2 && (f += 2);
      let p = (e[s + 6] << 8 | e[s + 7] << 0) >> 12 - f & 1, m = [2, 1, 2, 3, 3, 4, 4, 5][u] + p;
      t = new vA(), t.sampling_frequency = a, t.channel_count = m, t.channel_mode = u, t.bit_stream_identification = d, t.low_frequency_effects_channel_on = p, t.bit_stream_mode = h, t.frame_size_code = o, t.data = e.subarray(s, s + c);
    }
    return t;
  }
  hasIncompleteData() {
    return this.has_last_incomplete_data;
  }
  getIncompleteData() {
    return this.has_last_incomplete_data ? this.data_.subarray(this.current_syncword_offset_) : null;
  }
}
class TA {
  constructor(e) {
    y(this, "config");
    y(this, "sampling_rate");
    y(this, "bit_stream_identification");
    y(this, "bit_stream_mode");
    y(this, "low_frequency_effects_channel_on");
    y(this, "channel_count");
    y(this, "channel_mode");
    y(this, "codec_mimetype");
    y(this, "original_codec_mimetype");
    let t = null;
    t = [
      e.sampling_rate_code << 6 | e.bit_stream_identification << 1 | e.bit_stream_mode >> 2,
      (e.bit_stream_mode & 3) << 6 | e.channel_mode << 3 | e.low_frequency_effects_channel_on << 2 | e.frame_size_code >> 4,
      e.frame_size_code << 4 & 224
    ], this.config = t, this.sampling_rate = e.sampling_frequency, this.bit_stream_identification = e.bit_stream_identification, this.bit_stream_mode = e.bit_stream_mode, this.low_frequency_effects_channel_on = e.low_frequency_effects_channel_on, this.channel_count = e.channel_count, this.channel_mode = e.channel_mode, this.codec_mimetype = "ac-3", this.original_codec_mimetype = "ac-3";
  }
}
class bA {
  constructor() {
    y(this, "sampling_frequency");
    y(this, "sampling_rate_code");
    y(this, "bit_stream_identification");
    y(this, "low_frequency_effects_channel_on");
    y(this, "num_blks");
    y(this, "frame_size");
    y(this, "channel_count");
    y(this, "channel_mode");
    y(this, "data");
  }
}
class AA {
  constructor(e) {
    y(this, "TAG", "EAC3Parser");
    y(this, "data_");
    y(this, "current_syncword_offset_");
    y(this, "eof_flag_");
    y(this, "has_last_incomplete_data");
    this.data_ = e, this.current_syncword_offset_ = this.findNextSyncwordOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not found AC3 syncword until payload end");
  }
  findNextSyncwordOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 7 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      if ((i[t + 0] << 8 | i[t + 1] << 0) === 2935)
        return t;
      t++;
    }
  }
  readNextEAC3Frame() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_syncword_offset_, n = new pi(e.subarray(s + 2));
      n.readBits(2), n.readBits(3);
      let a = n.readBits(11) + 1 << 1, o = n.readBits(2), c = null, l = null;
      o === 3 ? (o = n.readBits(2), c = [24e3, 22060, 16e3][o], l = 3) : (c = [48e3, 44100, 32e3][o], l = n.readBits(2));
      let d = n.readBits(3), h = n.readBits(1), u = n.readBits(5);
      if (s + a > this.data_.byteLength) {
        this.eof_flag_ = !0, this.has_last_incomplete_data = !0;
        break;
      }
      let f = this.findNextSyncwordOffset(s + a);
      this.current_syncword_offset_ = f;
      let p = [2, 1, 2, 3, 3, 4, 4, 5][d] + h;
      n.destroy(), t = new bA(), t.sampling_frequency = c, t.channel_count = p, t.channel_mode = d, t.bit_stream_identification = u, t.low_frequency_effects_channel_on = h, t.frame_size = a, t.num_blks = [1, 2, 3, 6][l], t.data = e.subarray(s, s + a);
    }
    return t;
  }
  hasIncompleteData() {
    return this.has_last_incomplete_data;
  }
  getIncompleteData() {
    return this.has_last_incomplete_data ? this.data_.subarray(this.current_syncword_offset_) : null;
  }
}
class CA {
  constructor(e) {
    y(this, "config");
    y(this, "sampling_rate");
    y(this, "bit_stream_identification");
    y(this, "num_blks");
    y(this, "low_frequency_effects_channel_on");
    y(this, "channel_count");
    y(this, "channel_mode");
    y(this, "codec_mimetype");
    y(this, "original_codec_mimetype");
    let t = null;
    const i = Math.floor(e.frame_size * e.sampling_frequency / (e.num_blks * 16));
    t = [
      i & 255,
      i & 248,
      // num_ind_sub = zero
      e.sampling_rate_code << 6 | e.bit_stream_identification << 1 | 0,
      0 | e.channel_mode << 1 | e.low_frequency_effects_channel_on << 0,
      0
    ], this.config = t, this.sampling_rate = e.sampling_frequency, this.bit_stream_identification = e.bit_stream_identification, this.num_blks = e.num_blks, this.low_frequency_effects_channel_on = e.low_frequency_effects_channel_on, this.channel_count = e.channel_count, this.channel_mode = e.channel_mode, this.codec_mimetype = "ec-3", this.original_codec_mimetype = "ec-3";
  }
}
class RA {
  constructor() {
    y(this, "pid");
    y(this, "stream_id");
    y(this, "pts");
    y(this, "dts");
    y(this, "access_units");
    y(this, "data");
    y(this, "len");
  }
}
const IA = (r) => {
  let e = [], t = 0;
  for (; t + 5 < r.byteLength; ) {
    let i = r[t + 0], s = r[t + 1], n = r[t + 2], a = r[t + 3] << 8 | r[t + 4] << 0, o = r.slice(t + 5, t + 5 + a);
    e.push({
      service_id: i,
      sequence_number: s,
      flags: n,
      data: o
    }), t += 5 + a;
  }
  return e;
};
class Cd {
  constructor(e) {
    y(this, "TAG", "AV1OBUInMpegTsParser");
    y(this, "data_");
    y(this, "current_startcode_offset_", 0);
    y(this, "eof_flag_", !1);
    this.data_ = e, this.current_startcode_offset_ = this.findNextStartCodeOffset(0), this.eof_flag_ && S.e(this.TAG, "Could not find AV1 startcode until payload end!");
  }
  static _ebsp2rbsp(e) {
    let t = e, i = t.byteLength, s = new Uint8Array(i), n = 0;
    for (let a = 0; a < i; a++)
      a >= 2 && t[a] === 3 && t[a - 1] === 0 && t[a - 2] === 0 || (s[n] = t[a], n++);
    return new Uint8Array(s.buffer, 0, n);
  }
  findNextStartCodeOffset(e) {
    let t = e, i = this.data_;
    for (; ; ) {
      if (t + 2 >= i.byteLength)
        return this.eof_flag_ = !0, i.byteLength;
      if ((i[t + 0] << 16 | i[t + 1] << 8 | i[t + 2]) === 1)
        return t;
      t++;
    }
  }
  readNextOBUPayload() {
    let e = this.data_, t = null;
    for (; t == null && !this.eof_flag_; ) {
      let s = this.current_startcode_offset_ + 3, n = this.findNextStartCodeOffset(s);
      this.current_startcode_offset_ = n, t = Cd._ebsp2rbsp(e.subarray(s, n));
    }
    return t;
  }
}
class LA {
  constructor() {
    y(this, "pid");
    y(this, "stream_id");
    y(this, "pts");
    y(this, "dts");
    y(this, "lang");
    y(this, "data");
    y(this, "len");
  }
}
let cf = class extends $b {
  constructor(t, i) {
    super();
    y(this, "TAG", "TSDemuxer");
    y(this, "config_");
    y(this, "ts_packet_size_");
    y(this, "sync_offset_");
    y(this, "first_parse_", !0);
    y(this, "media_info_", new Gs());
    y(this, "timescale_", 90);
    y(this, "duration_", 0);
    y(this, "pat_", null);
    y(this, "current_program_");
    y(this, "current_pmt_pid_", -1);
    y(this, "pmt_", null);
    y(this, "program_pmt_map_", {});
    y(this, "pes_slice_queues_", {});
    y(this, "section_slice_queues_", {});
    y(this, "video_metadata_", {
      vps: void 0,
      sps: void 0,
      pps: void 0,
      av1c: void 0,
      details: void 0
    });
    y(this, "audio_metadata_", {
      codec: void 0,
      audio_object_type: void 0,
      sampling_freq_index: void 0,
      sampling_frequency: void 0,
      channel_config: void 0
    });
    y(this, "last_pcr_");
    y(this, "last_pcr_base_", NaN);
    y(this, "timestamp_offset_", 0);
    y(this, "audio_last_sample_pts_");
    y(this, "aac_last_incomplete_data_", null);
    y(this, "has_video_", !1);
    y(this, "has_audio_", !1);
    y(this, "video_init_segment_dispatched_", !1);
    y(this, "audio_init_segment_dispatched_", !1);
    y(this, "video_metadata_changed_", !1);
    y(this, "audio_metadata_changed_", !1);
    y(this, "loas_previous_frame", null);
    y(this, "video_track_", { type: "video", id: 1, sequenceNumber: 0, samples: [], length: 0 });
    y(this, "audio_track_", { type: "audio", id: 2, sequenceNumber: 0, samples: [], length: 0 });
    this.ts_packet_size_ = t.ts_packet_size, this.sync_offset_ = t.sync_offset, this.config_ = i;
  }
  destroy() {
    this.media_info_ = null, this.pes_slice_queues_ = null, this.section_slice_queues_ = null, this.video_metadata_ = null, this.audio_metadata_ = null, this.aac_last_incomplete_data_ = null, this.video_track_ = null, this.audio_track_ = null, super.destroy();
  }
  static probe(t) {
    let i = new Uint8Array(t), s = -1, n = 188;
    if (i.byteLength <= 3 * n)
      return { needMoreData: !0 };
    for (; s === -1; ) {
      let a = Math.min(1e3, i.byteLength - 3 * n);
      for (let o = 0; o < a; )
        if (i[o] === 71 && i[o + n] === 71 && i[o + 2 * n] === 71) {
          s = o;
          break;
        } else
          o++;
      if (s === -1)
        if (n === 188)
          n = 192;
        else if (n === 192)
          n = 204;
        else
          break;
    }
    return s === -1 ? { match: !1 } : (n === 192 && s >= 4 ? (S.v("TSDemuxer", "ts_packet_size = 192, m2ts mode"), s -= 4) : n === 204 && S.v("TSDemuxer", "ts_packet_size = 204, RS encoded MPEG2-TS stream"), {
      match: !0,
      consumed: 0,
      ts_packet_size: n,
      sync_offset: s
    });
  }
  bindDataSource(t) {
    return t.onDataArrival = this.parseChunks.bind(this), this;
  }
  resetMediaInfo() {
    this.media_info_ = new Gs();
  }
  parseChunks(t, i) {
    if (!this.onError || !this.onMediaInfo || !this.onTrackMetadata || !this.onDataAvailable)
      throw new qe("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");
    let s = 0;
    for (this.first_parse_ && (this.first_parse_ = !1, s = this.sync_offset_); s + this.ts_packet_size_ <= t.byteLength; ) {
      let n = i + s;
      this.ts_packet_size_ === 192 && (s += 4);
      let a = new Uint8Array(t, s, 188), o = a[0];
      if (o !== 71) {
        S.e(this.TAG, `sync_byte = ${o}, not 0x47`);
        break;
      }
      let c = (a[1] & 64) >>> 6;
      (a[1] & 32) >>> 5;
      let l = (a[1] & 31) << 8 | a[2], d = (a[3] & 48) >>> 4, h = a[3] & 15, u = !!(this.pmt_ && this.pmt_.pcr_pid === l), f = {}, p = 4;
      if (d == 2 || d == 3) {
        let m = a[4];
        if (m > 0 && (u || d == 3) && (f.discontinuity_indicator = (a[5] & 128) >>> 7, f.random_access_indicator = (a[5] & 64) >>> 6, f.elementary_stream_priority_indicator = (a[5] & 32) >>> 5, (a[5] & 16) >>> 4)) {
          let x = this.getPcrBase(a), _ = (a[10] & 1) << 8 | a[11], v = x * 300 + _;
          this.last_pcr_ = v;
        }
        if (d == 2 || 5 + m === 188) {
          s += 188, this.ts_packet_size_ === 204 && (s += 16);
          continue;
        } else
          p = 5 + m;
      }
      if (d == 1 || d == 3) {
        if (l === 0 || // PAT (pid === 0)
        l === this.current_pmt_pid_ || // PMT
        this.pmt_ != null && this.pmt_.pid_stream_type[l] === Ne.kSCTE35) {
          let m = 188 - p;
          this.handleSectionSlice(
            t,
            s + p,
            m,
            {
              pid: l,
              file_position: n,
              payload_unit_start_indicator: c,
              continuity_conunter: h,
              random_access_indicator: f.random_access_indicator
            }
          );
        } else if (this.pmt_ != null && this.pmt_.pid_stream_type[l] != null) {
          let m = 188 - p, g = this.pmt_.pid_stream_type[l];
          (l === this.pmt_.common_pids.h264 || l === this.pmt_.common_pids.h265 || l === this.pmt_.common_pids.av1 || l === this.pmt_.common_pids.adts_aac || l === this.pmt_.common_pids.loas_aac || l === this.pmt_.common_pids.ac3 || l === this.pmt_.common_pids.eac3 || l === this.pmt_.common_pids.opus || l === this.pmt_.common_pids.mp3 || this.pmt_.pes_private_data_pids[l] === !0 || this.pmt_.timed_id3_pids[l] === !0 || this.pmt_.pgs_pids[l] === !0 || this.pmt_.synchronous_klv_pids[l] === !0 || this.pmt_.asynchronous_klv_pids[l] === !0) && this.handlePESSlice(
            t,
            s + p,
            m,
            {
              pid: l,
              stream_type: g,
              file_position: n,
              payload_unit_start_indicator: c,
              continuity_conunter: h,
              random_access_indicator: f.random_access_indicator
            }
          );
        }
      }
      s += 188, this.ts_packet_size_ === 204 && (s += 16);
    }
    return this.dispatchAudioVideoMediaSegment(), s;
  }
  handleSectionSlice(t, i, s, n) {
    let a = new Uint8Array(t, i, s), o = this.section_slice_queues_[n.pid];
    if (n.payload_unit_start_indicator) {
      let c = a[0];
      if (o != null && o.total_length !== 0) {
        let l = new Uint8Array(t, i + 1, Math.min(s, c));
        o.slices.push(l), o.total_length += l.byteLength, o.total_length === o.expected_length ? this.emitSectionSlices(o, n) : this.clearSlices(o, n);
      }
      for (let l = 1 + c; l < a.byteLength && a[l + 0] !== 255; ) {
        let h = (a[l + 1] & 15) << 8 | a[l + 2];
        this.section_slice_queues_[n.pid] = new of(), o = this.section_slice_queues_[n.pid], o.expected_length = h + 3, o.file_position = n.file_position, o.random_access_indicator = n.random_access_indicator;
        let u = new Uint8Array(t, i + l, Math.min(s - l, o.expected_length - o.total_length));
        o.slices.push(u), o.total_length += u.byteLength, o.total_length === o.expected_length ? this.emitSectionSlices(o, n) : o.total_length >= o.expected_length && this.clearSlices(o, n), l += u.byteLength;
      }
    } else if (o != null && o.total_length !== 0) {
      let c = new Uint8Array(t, i, Math.min(s, o.expected_length - o.total_length));
      o.slices.push(c), o.total_length += c.byteLength, o.total_length === o.expected_length ? this.emitSectionSlices(o, n) : o.total_length >= o.expected_length && this.clearSlices(o, n);
    }
  }
  handlePESSlice(t, i, s, n) {
    let a = new Uint8Array(t, i, s), o = a[0] << 16 | a[1] << 8 | a[2];
    a[3];
    let c = a[4] << 8 | a[5];
    if (n.payload_unit_start_indicator) {
      if (o !== 1) {
        S.e(this.TAG, `handlePESSlice: packet_start_code_prefix should be 1 but with value ${o}`);
        return;
      }
      let d = this.pes_slice_queues_[n.pid];
      d && (d.expected_length === 0 || d.expected_length === d.total_length ? this.emitPESSlices(d, n) : this.clearSlices(d, n)), this.pes_slice_queues_[n.pid] = new of(), this.pes_slice_queues_[n.pid].file_position = n.file_position, this.pes_slice_queues_[n.pid].random_access_indicator = n.random_access_indicator;
    }
    if (this.pes_slice_queues_[n.pid] == null)
      return;
    let l = this.pes_slice_queues_[n.pid];
    l.slices.push(a), n.payload_unit_start_indicator && (l.expected_length = c === 0 ? 0 : c + 6), l.total_length += a.byteLength, l.expected_length > 0 && l.expected_length === l.total_length ? this.emitPESSlices(l, n) : l.expected_length > 0 && l.expected_length < l.total_length && this.clearSlices(l, n);
  }
  emitSectionSlices(t, i) {
    let s = new Uint8Array(t.total_length);
    for (let a = 0, o = 0; a < t.slices.length; a++) {
      let c = t.slices[a];
      s.set(c, o), o += c.byteLength;
    }
    t.slices = [], t.expected_length = -1, t.total_length = 0;
    let n = new zb();
    n.pid = i.pid, n.data = s, n.file_position = t.file_position, n.random_access_indicator = t.random_access_indicator, this.parseSection(n);
  }
  emitPESSlices(t, i) {
    let s = new Uint8Array(t.total_length);
    for (let a = 0, o = 0; a < t.slices.length; a++) {
      let c = t.slices[a];
      s.set(c, o), o += c.byteLength;
    }
    t.slices = [], t.expected_length = -1, t.total_length = 0;
    let n = new Yb();
    n.pid = i.pid, n.data = s, n.stream_type = i.stream_type, n.file_position = t.file_position, n.random_access_indicator = t.random_access_indicator, this.parsePES(n);
  }
  clearSlices(t, i) {
    t.slices = [], t.expected_length = -1, t.total_length = 0;
  }
  parseSection(t) {
    let i = t.data, s = t.pid;
    s === 0 ? this.parsePAT(i) : s === this.current_pmt_pid_ ? this.parsePMT(i) : this.pmt_ != null && this.pmt_.scte_35_pids[s] && this.parseSCTE35(i);
  }
  parsePES(t) {
    let i = t.data, s = i[0] << 16 | i[1] << 8 | i[2], n = i[3], a = i[4] << 8 | i[5];
    if (s !== 1) {
      S.e(this.TAG, `parsePES: packet_start_code_prefix should be 1 but with value ${s}`);
      return;
    }
    if (n !== 188 && n !== 190 && n !== 191 && n !== 240 && n !== 241 && n !== 255 && n !== 242 && n !== 248) {
      (i[6] & 48) >>> 4;
      let o = (i[7] & 192) >>> 6, c = i[8], l, d;
      (o === 2 || o === 3) && (l = this.getTimestamp(i, 9), d = o === 3 ? this.getTimestamp(i, 14) : l);
      let h = 9 + c, u;
      if (a !== 0) {
        if (a < 3 + c) {
          S.v(this.TAG, "Malformed PES: PES_packet_length < 3 + PES_header_data_length");
          return;
        }
        u = a - 3 - c;
      } else
        u = i.byteLength - h;
      let f = i.subarray(h, h + u);
      switch (t.stream_type) {
        case Ne.kMPEG1Audio:
        case Ne.kMPEG2Audio:
          this.parseMP3Payload(f, l);
          break;
        case Ne.kPESPrivateData:
          this.pmt_.common_pids.av1 === t.pid ? this.parseAV1Payload(f, l, d, t.file_position, t.random_access_indicator) : this.pmt_.common_pids.opus === t.pid ? this.parseOpusPayload(f, l) : this.pmt_.common_pids.ac3 === t.pid ? this.parseAC3Payload(f, l) : this.pmt_.common_pids.eac3 === t.pid ? this.parseEAC3Payload(f, l) : this.pmt_.asynchronous_klv_pids[t.pid] ? this.parseAsynchronousKLVMetadataPayload(f, t.pid, n) : this.pmt_.smpte2038_pids[t.pid] ? this.parseSMPTE2038MetadataPayload(f, l, d, t.pid, n) : this.parsePESPrivateDataPayload(f, l, d, t.pid, n);
          break;
        case Ne.kADTSAAC:
          this.parseADTSAACPayload(f, l);
          break;
        case Ne.kLOASAAC:
          this.parseLOASAACPayload(f, l);
          break;
        case Ne.kAC3:
          this.parseAC3Payload(f, l);
          break;
        case Ne.kEAC3:
          this.parseEAC3Payload(f, l);
          break;
        case Ne.kMetadata:
          this.pmt_.timed_id3_pids[t.pid] ? this.parseTimedID3MetadataPayload(f, l, d, t.pid, n) : this.pmt_.synchronous_klv_pids[t.pid] && this.parseSynchronousKLVMetadataPayload(f, l, d, t.pid, n);
          break;
        case Ne.kPGS:
          this.parsePGSPayload(f, l, d, t.pid, n, this.pmt_.pgs_langs[t.pid]);
          break;
        case Ne.kH264:
          this.parseH264Payload(f, l, d, t.file_position, t.random_access_indicator);
          break;
        case Ne.kH265:
          this.parseH265Payload(f, l, d, t.file_position, t.random_access_indicator);
          break;
      }
    } else if ((n === 188 || n === 191 || n === 240 || n === 241 || n === 255 || n === 242 || n === 248) && t.stream_type === Ne.kPESPrivateData) {
      let o = 6, c;
      a !== 0 ? c = a : c = i.byteLength - o;
      let l = i.subarray(o, o + c);
      this.parsePESPrivateDataPayload(l, void 0, void 0, t.pid, n);
    }
  }
  parsePAT(t) {
    let i = t[0];
    if (i !== 0) {
      S.e(this.TAG, `parsePAT: table_id ${i} is not corresponded to PAT!`);
      return;
    }
    let s = (t[1] & 15) << 8 | t[2];
    t[3] << 8 | t[4];
    let n = (t[5] & 62) >>> 1, a = t[5] & 1, o = t[6];
    t[7];
    let c = null;
    if (a === 1 && o === 0)
      c = new Kb(), c.version_number = n;
    else if (c = this.pat_, c == null)
      return;
    let l = 8, d = s - 5 - 4, h = -1, u = -1;
    for (let f = l; f < l + d; f += 4) {
      let p = t[f] << 8 | t[f + 1], m = (t[f + 2] & 31) << 8 | t[f + 3];
      p === 0 ? c.network_pid = m : (c.program_pmt_pid[p] = m, h === -1 && (h = p), u === -1 && (u = m));
    }
    a === 1 && o === 0 && (this.pat_ == null && S.v(this.TAG, `Parsed first PAT: ${JSON.stringify(c)}`), this.pat_ = c, this.current_program_ = h, this.current_pmt_pid_ = u);
  }
  parsePMT(t) {
    let i = t[0];
    if (i !== 2) {
      S.e(this.TAG, `parsePMT: table_id ${i} is not corresponded to PMT!`);
      return;
    }
    let s = (t[1] & 15) << 8 | t[2], n = t[3] << 8 | t[4], a = (t[5] & 62) >>> 1, o = t[5] & 1, c = t[6];
    t[7];
    let l = null;
    if (o === 1 && c === 0)
      l = new Xb(), l.program_number = n, l.version_number = a, this.program_pmt_map_[n] = l;
    else if (l = this.program_pmt_map_[n], l == null)
      return;
    l.pcr_pid = (t[8] & 31) << 8 | t[9];
    let d = (t[10] & 15) << 8 | t[11], h = 12 + d, u = s - 9 - d - 4;
    for (let f = h; f < h + u; ) {
      let p = t[f], m = (t[f + 1] & 31) << 8 | t[f + 2], g = (t[f + 3] & 15) << 8 | t[f + 4];
      l.pid_stream_type[m] = p;
      let x = l.common_pids.h264 || l.common_pids.h265, _ = l.common_pids.adts_aac || l.common_pids.loas_aac || l.common_pids.ac3 || l.common_pids.eac3 || l.common_pids.opus || l.common_pids.mp3;
      if (p === Ne.kH264 && !x)
        l.common_pids.h264 = m;
      else if (p === Ne.kH265 && !x)
        l.common_pids.h265 = m;
      else if (p === Ne.kADTSAAC && !_)
        l.common_pids.adts_aac = m;
      else if (p === Ne.kLOASAAC && !_)
        l.common_pids.loas_aac = m;
      else if (p === Ne.kAC3 && !_)
        l.common_pids.ac3 = m;
      else if (p === Ne.kEAC3 && !_)
        l.common_pids.eac3 = m;
      else if ((p === Ne.kMPEG1Audio || p === Ne.kMPEG2Audio) && !_)
        l.common_pids.mp3 = m;
      else if (p === Ne.kPESPrivateData) {
        if (l.pes_private_data_pids[m] = !0, g > 0) {
          for (let E = f + 5; E < f + 5 + g; ) {
            let b = t[E + 0], A = t[E + 1];
            if (b === 5) {
              let C = String.fromCharCode(...Array.from(t.subarray(E + 2, E + 2 + A)));
              C === "VANC" ? l.smpte2038_pids[m] = !0 : C === "AV01" ? l.common_pids.av1 = m : C === "Opus" ? l.common_pids.opus = m : C === "KLVA" && (l.asynchronous_klv_pids[m] = !0);
            } else if (b === 127) {
              if (m === l.common_pids.opus) {
                let C = t[E + 2], I = null;
                if (C === 128 && (I = t[E + 3]), I == null) {
                  S.e(this.TAG, "Not Supported Opus channel count.");
                  continue;
                }
                const L = {
                  codec: "opus",
                  channel_count: I & 15 ? I & 15 : 2,
                  channel_config_code: I,
                  sample_rate: 48e3
                }, R = {
                  codec: "opus",
                  meta: L
                };
                this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = L, this.dispatchAudioInitSegment(R)) : this.detectAudioMetadataChange(R) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(R));
              }
            } else b === 128 && m === l.common_pids.av1 && (this.video_metadata_.av1c = t.subarray(E + 2, E + 2 + A));
            E += 2 + A;
          }
          let v = t.subarray(f + 5, f + 5 + g);
          this.dispatchPESPrivateDataDescriptor(m, p, v);
        }
      } else if (p === Ne.kMetadata) {
        if (g > 0)
          for (let v = f + 5; v < f + 5 + g; ) {
            let E = t[v + 0], b = t[v + 1];
            if (E === 38) {
              let A = t[v + 2] << 8 | t[v + 3] << 0, C = null;
              A === 65535 && (C = String.fromCharCode(...Array.from(t.subarray(v + 4, v + 4 + 4))));
              let I = t[v + 4 + (A === 65535 ? 4 : 0)], L = null;
              if (I === 255) {
                let R = 4 + (A === 65535 ? 4 : 0) + 1;
                L = String.fromCharCode(...Array.from(t.subarray(v + R, v + R + 4)));
              }
              C === "ID3 " && L === "ID3 " ? l.timed_id3_pids[m] = !0 : L === "KLVA" && (l.synchronous_klv_pids[m] = !0);
            }
            v += 2 + b;
          }
      } else if (p === Ne.kSCTE35)
        l.scte_35_pids[m] = !0;
      else if (p === Ne.kPGS) {
        if (l.pgs_langs[m] = "und", g > 0)
          for (let v = f + 5; v < f + 5 + g; ) {
            let E = t[v + 0], b = t[v + 1];
            if (E === 10) {
              const A = String.fromCharCode(...Array.from(t.slice(v + 2, v + 5)));
              l.pgs_langs[m] = A;
            }
            v += 2 + b;
          }
        l.pgs_pids[m] = !0;
      }
      f += 5 + g;
    }
    n === this.current_program_ && (this.pmt_ == null && S.v(this.TAG, `Parsed first PMT: ${JSON.stringify(l)}`), this.pmt_ = l, (l.common_pids.h264 || l.common_pids.h265 || l.common_pids.av1) && (this.has_video_ = !0), (l.common_pids.adts_aac || l.common_pids.loas_aac || l.common_pids.ac3 || l.common_pids.opus || l.common_pids.mp3) && (this.has_audio_ = !0));
  }
  parseSCTE35(t) {
    const i = gA(t);
    if (i.pts != null) {
      let s = Math.floor(i.pts / this.timescale_);
      i.pts = s;
    } else
      i.nearest_pts = this.getNearestTimestampMilliseconds();
    this.onSCTE35Metadata && this.onSCTE35Metadata(i);
  }
  parseAV1Payload(t, i, s, n, a) {
    let o = new Cd(t), c = null, l = [], d = 0, h = !1, u = null;
    for (; (c = o.readNextOBUPayload()) != null; ) {
      if (u = Xt.parseOBUs(c, this.video_metadata_.details), u && u.keyframe === !0)
        if (this.video_init_segment_dispatched_) {
          if (this.detectVideoMetadataChange(null, u) === !0) {
            this.video_metadata_changed_ = !0, this.dispatchVideoMediaSegment();
            const m = new Uint8Array(new ArrayBuffer(this.video_metadata_.av1c.byteLength + u.sequence_header_data.byteLength));
            m.set(this.video_metadata_.av1c, 0), m.set(u.sequence_header_data, this.video_metadata_.av1c.byteLength), u.av1c = m, this.dispatchVideoInitSegment();
          }
        } else {
          const m = new Uint8Array(new ArrayBuffer(this.video_metadata_.av1c.byteLength + u.sequence_header_data.byteLength));
          m.set(this.video_metadata_.av1c, 0), m.set(u.sequence_header_data, this.video_metadata_.av1c.byteLength), u.av1c = m, this.video_metadata_.details = u, this.dispatchVideoInitSegment();
        }
      this.video_metadata_.details = u, h || (h = u.keyframe), l.push({ data: c }), d += c.byteLength;
    }
    let f = Math.floor(i / this.timescale_), p = Math.floor(s / this.timescale_);
    if (l.length) {
      let m = this.video_track_, g = {
        units: l,
        length: d,
        isKeyframe: h,
        dts: p,
        pts: f,
        cts: f - p,
        file_position: n
      };
      m.samples.push(g), m.length += d;
    }
  }
  parseH264Payload(t, i, s, n, a) {
    let o = new wb(t), c = null, l = [], d = 0, h = !1;
    for (; (c = o.readNextNaluPayload()) != null; ) {
      let p = new kb(c);
      if (p.type === zt.kSliceSPS) {
        let m = Ki.parseSPS(c.data);
        this.video_init_segment_dispatched_ ? this.detectVideoMetadataChange(p, m) === !0 && (S.v(this.TAG, "H264: Critical h264 metadata has been changed, attempt to re-generate InitSegment"), this.video_metadata_changed_ = !0, this.video_metadata_ = { vps: void 0, sps: p, pps: void 0, av1c: void 0, details: m }) : (this.video_metadata_.sps = p, this.video_metadata_.details = m);
      } else p.type === zt.kSlicePPS ? (!this.video_init_segment_dispatched_ || this.video_metadata_changed_) && (this.video_metadata_.pps = p, this.video_metadata_.sps && this.video_metadata_.pps && (this.video_metadata_changed_ && this.dispatchVideoMediaSegment(), this.dispatchVideoInitSegment())) : (p.type === zt.kSliceIDR || p.type === zt.kSliceNonIDR && a === 1) && (h = !0);
      this.video_init_segment_dispatched_ && (l.push(p), d += p.data.byteLength);
    }
    let u = Math.floor(i / this.timescale_), f = Math.floor(s / this.timescale_);
    if (l.length) {
      let p = this.video_track_, m = {
        units: l,
        length: d,
        isKeyframe: h,
        dts: f,
        pts: u,
        cts: u - f,
        file_position: n
      };
      p.samples.push(m), p.length += d;
    }
  }
  parseH265Payload(t, i, s, n, a) {
    let o = new Wb(t), c = null, l = [], d = 0, h = !1;
    for (; (c = o.readNextNaluPayload()) != null; ) {
      let p = new Vb(c);
      if (p.type === Pt.kSliceVPS) {
        if (!this.video_init_segment_dispatched_) {
          let m = di.parseVPS(c.data);
          this.video_metadata_.vps = p, this.video_metadata_.details = {
            ...this.video_metadata_.details,
            ...m
          };
        }
      } else if (p.type === Pt.kSliceSPS) {
        let m = di.parseSPS(c.data);
        this.video_init_segment_dispatched_ ? this.detectVideoMetadataChange(p, m) === !0 && (S.v(this.TAG, "H265: Critical h265 metadata has been changed, attempt to re-generate InitSegment"), this.video_metadata_changed_ = !0, this.video_metadata_ = { vps: void 0, sps: p, pps: void 0, av1c: void 0, details: m }) : (this.video_metadata_.sps = p, this.video_metadata_.details = {
          ...this.video_metadata_.details,
          ...m
        });
      } else if (p.type === Pt.kSlicePPS) {
        if (!this.video_init_segment_dispatched_ || this.video_metadata_changed_) {
          let m = di.parsePPS(c.data);
          this.video_metadata_.pps = p, this.video_metadata_.details = {
            ...this.video_metadata_.details,
            ...m
          }, this.video_metadata_.vps && this.video_metadata_.sps && this.video_metadata_.pps && (this.video_metadata_changed_ && this.dispatchVideoMediaSegment(), this.dispatchVideoInitSegment());
        }
      } else (p.type === Pt.kSliceIDR_W_RADL || p.type === Pt.kSliceIDR_N_LP || p.type === Pt.kSliceCRA_NUT) && (h = !0);
      this.video_init_segment_dispatched_ && (l.push(p), d += p.data.byteLength);
    }
    let u = Math.floor(i / this.timescale_), f = Math.floor(s / this.timescale_);
    if (l.length) {
      let p = this.video_track_, m = {
        units: l,
        length: d,
        isKeyframe: h,
        dts: f,
        pts: u,
        cts: u - f,
        file_position: n
      };
      p.samples.push(m), p.length += d;
    }
  }
  detectVideoMetadataChange(t, i) {
    if (i.codec_mimetype !== this.video_metadata_.details.codec_mimetype)
      return S.v(this.TAG, `Video: Codec mimeType changed from ${this.video_metadata_.details.codec_mimetype} to ${i.codec_mimetype}`), !0;
    if (i.codec_size.width !== this.video_metadata_.details.codec_size.width || i.codec_size.height !== this.video_metadata_.details.codec_size.height) {
      let s = this.video_metadata_.details.codec_size, n = i.codec_size;
      return S.v(this.TAG, `Video: Coded Resolution changed from ${s.width}x${s.height} to ${n.width}x${n.height}`), !0;
    }
    return i.present_size.width !== this.video_metadata_.details.present_size.width ? (S.v(this.TAG, `Video: Present resolution width changed from ${this.video_metadata_.details.present_size.width} to ${i.present_size.width}`), !0) : !1;
  }
  isInitSegmentDispatched() {
    return this.has_video_ && this.has_audio_ ? this.video_init_segment_dispatched_ && this.audio_init_segment_dispatched_ : this.has_video_ && !this.has_audio_ ? this.video_init_segment_dispatched_ : !this.has_video_ && this.has_audio_ ? this.audio_init_segment_dispatched_ : !1;
  }
  dispatchVideoInitSegment() {
    let t = this.video_metadata_.details, i = {};
    i.type = "video", i.id = this.video_track_.id, i.timescale = 1e3, i.duration = this.duration_, i.codecWidth = t.codec_size.width, i.codecHeight = t.codec_size.height, i.presentWidth = t.present_size.width, i.presentHeight = t.present_size.height, i.profile = t.profile_string, i.level = t.level_string, i.bitDepth = t.bit_depth, i.chromaFormat = t.chroma_format, i.sarRatio = t.sar_ratio, i.frameRate = t.frame_rate;
    let s = i.frameRate.fps_den, n = i.frameRate.fps_num;
    if (i.refSampleDuration = 1e3 * (s / n), i.codec = t.codec_mimetype, this.video_metadata_.av1c)
      i.av1c = this.video_metadata_.av1c, this.video_init_segment_dispatched_ == !1 && S.v(this.TAG, `Generated first AV1 for mimeType: ${i.codec}`);
    else if (this.video_metadata_.vps) {
      let o = this.video_metadata_.vps.data.subarray(4), c = this.video_metadata_.sps.data.subarray(4), l = this.video_metadata_.pps.data.subarray(4), d = new Hb(o, c, l, t);
      i.hvcc = d.getData(), this.video_init_segment_dispatched_ == !1 && S.v(this.TAG, `Generated first HEVCDecoderConfigurationRecord for mimeType: ${i.codec}`);
    } else {
      let o = this.video_metadata_.sps.data.subarray(4), c = this.video_metadata_.pps.data.subarray(4), l = new Mb(o, c, t);
      i.avcc = l.getData(), this.video_init_segment_dispatched_ == !1 && S.v(this.TAG, `Generated first AVCDecoderConfigurationRecord for mimeType: ${i.codec}`);
    }
    this.onTrackMetadata("video", i), this.video_init_segment_dispatched_ = !0, this.video_metadata_changed_ = !1;
    let a = this.media_info_;
    a.hasVideo = !0, a.width = i.codecWidth, a.height = i.codecHeight, a.fps = i.frameRate.fps, a.profile = i.profile, a.level = i.level, a.refFrames = t.ref_frames, a.chromaFormat = t.chroma_format_string, a.sarNum = i.sarRatio.width, a.sarDen = i.sarRatio.height, a.videoCodec = i.codec, a.hasAudio && a.audioCodec ? a.mimeType = `video/mp2t; codecs="${a.videoCodec},${a.audioCodec}"` : a.mimeType = `video/mp2t; codecs="${a.videoCodec}"`, a.isComplete() && this.onMediaInfo(a);
  }
  dispatchVideoMediaSegment() {
    this.isInitSegmentDispatched() && this.video_track_.length && this.onDataAvailable(null, this.video_track_);
  }
  dispatchAudioMediaSegment() {
    this.isInitSegmentDispatched() && this.audio_track_.length && this.onDataAvailable(this.audio_track_, null);
  }
  dispatchAudioVideoMediaSegment() {
    this.isInitSegmentDispatched() && (this.audio_track_.length || this.video_track_.length) && this.onDataAvailable(this.audio_track_, this.video_track_);
  }
  parseADTSAACPayload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    if (this.aac_last_incomplete_data_) {
      let d = new Uint8Array(t.byteLength + this.aac_last_incomplete_data_.byteLength);
      d.set(this.aac_last_incomplete_data_, 0), d.set(t, this.aac_last_incomplete_data_.byteLength), t = d;
    }
    let s, n;
    if (i != null && (n = i / this.timescale_), this.audio_metadata_.codec === "aac") {
      if (i == null && this.audio_last_sample_pts_ != null)
        s = 1024 / this.audio_metadata_.sampling_frequency * 1e3, n = this.audio_last_sample_pts_ + s;
      else if (i == null) {
        S.w(this.TAG, "AAC: Unknown pts");
        return;
      }
      if (this.aac_last_incomplete_data_ && this.audio_last_sample_pts_) {
        s = 1024 / this.audio_metadata_.sampling_frequency * 1e3;
        let d = this.audio_last_sample_pts_ + s;
        Math.abs(d - n) > 1 && (S.w(this.TAG, `AAC: Detected pts overlapped, expected: ${d}ms, PES pts: ${n}ms`), n = d);
      }
    }
    let a = new jb(t), o = null, c = n, l;
    for (; (o = a.readNextAACFrame()) != null; ) {
      s = 1024 / o.sampling_frequency * 1e3;
      const d = {
        codec: "aac",
        data: o
      };
      this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = {
        codec: "aac",
        audio_object_type: o.audio_object_type,
        sampling_freq_index: o.sampling_freq_index,
        sampling_frequency: o.sampling_frequency,
        channel_config: o.channel_config
      }, this.dispatchAudioInitSegment(d)) : this.detectAudioMetadataChange(d) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(d)), l = c;
      let h = Math.floor(c), u = {
        unit: o.data,
        length: o.data.byteLength,
        pts: h,
        dts: h
      };
      this.audio_track_.samples.push(u), this.audio_track_.length += o.data.byteLength, c += s;
    }
    a.hasIncompleteData() && (this.aac_last_incomplete_data_ = a.getIncompleteData()), l && (this.audio_last_sample_pts_ = l);
  }
  parseLOASAACPayload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    if (this.aac_last_incomplete_data_) {
      let d = new Uint8Array(t.byteLength + this.aac_last_incomplete_data_.byteLength);
      d.set(this.aac_last_incomplete_data_, 0), d.set(t, this.aac_last_incomplete_data_.byteLength), t = d;
    }
    let s, n;
    if (i != null && (n = i / this.timescale_), this.audio_metadata_.codec === "aac") {
      if (i == null && this.audio_last_sample_pts_ != null)
        s = 1024 / this.audio_metadata_.sampling_frequency * 1e3, n = this.audio_last_sample_pts_ + s;
      else if (i == null) {
        S.w(this.TAG, "AAC: Unknown pts");
        return;
      }
      if (this.aac_last_incomplete_data_ && this.audio_last_sample_pts_) {
        s = 1024 / this.audio_metadata_.sampling_frequency * 1e3;
        let d = this.audio_last_sample_pts_ + s;
        Math.abs(d - n) > 1 && (S.w(this.TAG, `AAC: Detected pts overlapped, expected: ${d}ms, PES pts: ${n}ms`), n = d);
      }
    }
    let a = new Qb(t), o = null, c = n, l;
    for (; (o = a.readNextAACFrame(this.loas_previous_frame ?? void 0)) != null; ) {
      this.loas_previous_frame = o, s = 1024 / o.sampling_frequency * 1e3;
      const d = {
        codec: "aac",
        data: o
      };
      this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = {
        codec: "aac",
        audio_object_type: o.audio_object_type,
        sampling_freq_index: o.sampling_freq_index,
        sampling_frequency: o.sampling_frequency,
        channel_config: o.channel_config
      }, this.dispatchAudioInitSegment(d)) : this.detectAudioMetadataChange(d) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(d)), l = c;
      let h = Math.floor(c), u = {
        unit: o.data,
        length: o.data.byteLength,
        pts: h,
        dts: h
      };
      this.audio_track_.samples.push(u), this.audio_track_.length += o.data.byteLength, c += s;
    }
    a.hasIncompleteData() && (this.aac_last_incomplete_data_ = a.getIncompleteData()), l && (this.audio_last_sample_pts_ = l);
  }
  parseAC3Payload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    let s, n;
    if (i != null && (n = i / this.timescale_), this.audio_metadata_.codec === "ac-3") {
      if (i == null && this.audio_last_sample_pts_ != null)
        s = 1536 / this.audio_metadata_.sampling_frequency * 1e3, n = this.audio_last_sample_pts_ + s;
      else if (i == null) {
        S.w(this.TAG, "AC3: Unknown pts");
        return;
      }
    }
    let a = new SA(t), o = null, c = n, l;
    for (; (o = a.readNextAC3Frame()) != null; ) {
      s = 1536 / o.sampling_frequency * 1e3;
      const d = {
        codec: "ac-3",
        data: o
      };
      this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = {
        codec: "ac-3",
        sampling_frequency: o.sampling_frequency,
        bit_stream_identification: o.bit_stream_identification,
        bit_stream_mode: o.bit_stream_mode,
        low_frequency_effects_channel_on: o.low_frequency_effects_channel_on,
        channel_mode: o.channel_mode
      }, this.dispatchAudioInitSegment(d)) : this.detectAudioMetadataChange(d) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(d)), l = c;
      let h = Math.floor(c), u = {
        unit: o.data,
        length: o.data.byteLength,
        pts: h,
        dts: h
      };
      this.audio_track_.samples.push(u), this.audio_track_.length += o.data.byteLength, c += s;
    }
    l && (this.audio_last_sample_pts_ = l);
  }
  parseEAC3Payload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    let s, n;
    if (i != null && (n = i / this.timescale_), this.audio_metadata_.codec === "ec-3") {
      if (i == null && this.audio_last_sample_pts_ != null)
        s = 256 * this.audio_metadata_.num_blks / this.audio_metadata_.sampling_frequency * 1e3, n = this.audio_last_sample_pts_ + s;
      else if (i == null) {
        S.w(this.TAG, "EAC3: Unknown pts");
        return;
      }
    }
    let a = new AA(t), o = null, c = n, l;
    for (; (o = a.readNextEAC3Frame()) != null; ) {
      s = 1536 / o.sampling_frequency * 1e3;
      const d = {
        codec: "ec-3",
        data: o
      };
      this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = {
        codec: "ec-3",
        sampling_frequency: o.sampling_frequency,
        bit_stream_identification: o.bit_stream_identification,
        low_frequency_effects_channel_on: o.low_frequency_effects_channel_on,
        num_blks: o.num_blks,
        channel_mode: o.channel_mode
      }, this.dispatchAudioInitSegment(d)) : this.detectAudioMetadataChange(d) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(d)), l = c;
      let h = Math.floor(c), u = {
        unit: o.data,
        length: o.data.byteLength,
        pts: h,
        dts: h
      };
      this.audio_track_.samples.push(u), this.audio_track_.length += o.data.byteLength, c += s;
    }
    l && (this.audio_last_sample_pts_ = l);
  }
  parseOpusPayload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    let s, n;
    if (i != null && (n = i / this.timescale_), this.audio_metadata_.codec === "opus") {
      if (i == null && this.audio_last_sample_pts_ != null)
        s = 20, n = this.audio_last_sample_pts_ + s;
      else if (i == null) {
        S.w(this.TAG, "Opus: Unknown pts");
        return;
      }
    }
    let a = n, o;
    for (let c = 0; c < t.length; ) {
      s = 20;
      const l = (t[c + 1] & 16) !== 0, d = (t[c + 1] & 8) !== 0;
      let h = c + 2, u = 0;
      for (; t[h] === 255; )
        u += 255, h += 1;
      u += t[h], h += 1, h += l ? 2 : 0, h += d ? 2 : 0, o = a;
      let f = Math.floor(a), p = t.slice(h, h + u), m = {
        unit: p,
        length: p.byteLength,
        pts: f,
        dts: f
      };
      this.audio_track_.samples.push(m), this.audio_track_.length += p.byteLength, a += s, c = h + u;
    }
    o && (this.audio_last_sample_pts_ = o);
  }
  parseMP3Payload(t, i) {
    if (this.has_video_ && !this.video_init_segment_dispatched_)
      return;
    let s = [44100, 48e3, 32e3, 0], n = [22050, 24e3, 16e3, 0], a = [11025, 12e3, 8e3, 0], o = t[1] >>> 3 & 3, c = (t[1] & 6) >> 1;
    (t[2] & 240) >>> 4;
    let l = (t[2] & 12) >>> 2, h = (t[3] >>> 6 & 3) !== 3 ? 2 : 1, u = 0, f = 34;
    switch (o) {
      case 0:
        u = a[l];
        break;
      case 2:
        u = n[l];
        break;
      case 3:
        u = s[l];
        break;
    }
    switch (c) {
      case 1:
        f = 34;
        break;
      case 2:
        f = 33;
        break;
      case 3:
        f = 32;
        break;
    }
    const p = new xA();
    p.object_type = f, p.sample_rate = u, p.channel_count = h, p.data = t;
    const m = {
      codec: "mp3",
      data: p
    };
    this.audio_init_segment_dispatched_ == !1 ? (this.audio_metadata_ = {
      codec: "mp3",
      object_type: f,
      sample_rate: u,
      channel_count: h
    }, this.dispatchAudioInitSegment(m)) : this.detectAudioMetadataChange(m) && (this.dispatchAudioMediaSegment(), this.dispatchAudioInitSegment(m));
    let g = {
      unit: t,
      length: t.byteLength,
      pts: i / this.timescale_,
      dts: i / this.timescale_
    };
    this.audio_track_.samples.push(g), this.audio_track_.length += t.byteLength;
  }
  detectAudioMetadataChange(t) {
    if (t.codec !== this.audio_metadata_.codec)
      return S.v(this.TAG, `Audio: Audio Codecs changed from ${this.audio_metadata_.codec} to ${t.codec}`), !0;
    if (t.codec === "aac" && this.audio_metadata_.codec === "aac") {
      const i = t.data;
      if (i.audio_object_type !== this.audio_metadata_.audio_object_type)
        return S.v(this.TAG, `AAC: AudioObjectType changed from ${this.audio_metadata_.audio_object_type} to ${i.audio_object_type}`), !0;
      if (i.sampling_freq_index !== this.audio_metadata_.sampling_freq_index)
        return S.v(this.TAG, `AAC: SamplingFrequencyIndex changed from ${this.audio_metadata_.sampling_freq_index} to ${i.sampling_freq_index}`), !0;
      if (i.channel_config !== this.audio_metadata_.channel_config)
        return S.v(this.TAG, `AAC: Channel configuration changed from ${this.audio_metadata_.channel_config} to ${i.channel_config}`), !0;
    } else if (t.codec === "ac-3" && this.audio_metadata_.codec === "ac-3") {
      const i = t.data;
      if (i.sampling_frequency !== this.audio_metadata_.sampling_frequency)
        return S.v(this.TAG, `AC3: Sampling Frequency changed from ${this.audio_metadata_.sampling_frequency} to ${i.sampling_frequency}`), !0;
      if (i.bit_stream_identification !== this.audio_metadata_.bit_stream_identification)
        return S.v(this.TAG, `AC3: Bit Stream Identification changed from ${this.audio_metadata_.bit_stream_identification} to ${i.bit_stream_identification}`), !0;
      if (i.bit_stream_mode !== this.audio_metadata_.bit_stream_mode)
        return S.v(this.TAG, `AC3: BitStream Mode changed from ${this.audio_metadata_.bit_stream_mode} to ${i.bit_stream_mode}`), !0;
      if (i.channel_mode !== this.audio_metadata_.channel_mode)
        return S.v(this.TAG, `AC3: Channel Mode changed from ${this.audio_metadata_.channel_mode} to ${i.channel_mode}`), !0;
      if (i.low_frequency_effects_channel_on !== this.audio_metadata_.low_frequency_effects_channel_on)
        return S.v(this.TAG, `AC3: Low Frequency Effects Channel On changed from ${this.audio_metadata_.low_frequency_effects_channel_on} to ${i.low_frequency_effects_channel_on}`), !0;
    } else if (t.codec === "opus" && this.audio_metadata_.codec === "opus") {
      const i = t.meta;
      if (i.sample_rate !== this.audio_metadata_.sample_rate)
        return S.v(this.TAG, `Opus: SamplingFrequencyIndex changed from ${this.audio_metadata_.sample_rate} to ${i.sample_rate}`), !0;
      if (i.channel_count !== this.audio_metadata_.channel_count)
        return S.v(this.TAG, `Opus: Channel count changed from ${this.audio_metadata_.channel_count} to ${i.channel_count}`), !0;
    } else if (t.codec === "mp3" && this.audio_metadata_.codec === "mp3") {
      const i = t.data;
      if (i.object_type !== this.audio_metadata_.object_type)
        return S.v(this.TAG, `MP3: AudioObjectType changed from ${this.audio_metadata_.object_type} to ${i.object_type}`), !0;
      if (i.sample_rate !== this.audio_metadata_.sample_rate)
        return S.v(this.TAG, `MP3: SamplingFrequencyIndex changed from ${this.audio_metadata_.sample_rate} to ${i.sample_rate}`), !0;
      if (i.channel_count !== this.audio_metadata_.channel_count)
        return S.v(this.TAG, `MP3: Channel count changed from ${this.audio_metadata_.channel_count} to ${i.channel_count}`), !0;
    }
    return !1;
  }
  dispatchAudioInitSegment(t) {
    let i = {};
    if (i.type = "audio", i.id = this.audio_track_.id, i.timescale = 1e3, i.duration = this.duration_, this.audio_metadata_.codec === "aac") {
      let n = t.codec === "aac" ? t.data : null, a = new Jb(n);
      i.audioSampleRate = a.sampling_rate, i.channelCount = a.channel_count, i.codec = a.codec_mimetype, i.originalCodec = a.original_codec_mimetype, i.config = a.config, i.refSampleDuration = 1024 / i.audioSampleRate * i.timescale;
    } else if (this.audio_metadata_.codec === "ac-3") {
      let n = t.codec === "ac-3" ? t.data : null, a = new TA(n);
      i.audioSampleRate = a.sampling_rate, i.channelCount = a.channel_count, i.codec = a.codec_mimetype, i.originalCodec = a.original_codec_mimetype, i.config = a.config, i.refSampleDuration = 1536 / i.audioSampleRate * i.timescale;
    } else if (this.audio_metadata_.codec === "ec-3") {
      let n = t.codec === "ec-3" ? t.data : null, a = new CA(n);
      i.audioSampleRate = a.sampling_rate, i.channelCount = a.channel_count, i.codec = a.codec_mimetype, i.originalCodec = a.original_codec_mimetype, i.config = a.config, i.refSampleDuration = 256 * a.num_blks / i.audioSampleRate * i.timescale;
    } else this.audio_metadata_.codec === "opus" ? (i.audioSampleRate = this.audio_metadata_.sample_rate, i.channelCount = this.audio_metadata_.channel_count, i.channelConfigCode = this.audio_metadata_.channel_config_code, i.codec = "opus", i.originalCodec = "opus", i.config = void 0, i.refSampleDuration = 20) : this.audio_metadata_.codec === "mp3" && (i.audioSampleRate = this.audio_metadata_.sample_rate, i.channelCount = this.audio_metadata_.channel_count, i.codec = "mp3", i.originalCodec = "mp3", i.config = void 0);
    this.audio_init_segment_dispatched_ == !1 && S.v(this.TAG, `Generated first AudioSpecificConfig for mimeType: ${i.codec}`), this.onTrackMetadata("audio", i), this.audio_init_segment_dispatched_ = !0, this.video_metadata_changed_ = !1;
    let s = this.media_info_;
    s.hasAudio = !0, s.audioCodec = i.originalCodec, s.audioSampleRate = i.audioSampleRate, s.audioChannelCount = i.channelCount, s.hasVideo && s.videoCodec ? s.mimeType = `video/mp2t; codecs="${s.videoCodec},${s.audioCodec}"` : s.mimeType = `video/mp2t; codecs="${s.audioCodec}"`, s.isComplete() && this.onMediaInfo(s);
  }
  dispatchPESPrivateDataDescriptor(t, i, s) {
    let n = new qb();
    n.pid = t, n.stream_type = i, n.descriptor = s, this.onPESPrivateDataDescriptor && this.onPESPrivateDataDescriptor(n);
  }
  parsePESPrivateDataPayload(t, i, s, n, a) {
    let o = new s0();
    if (o.pid = n, o.stream_id = a, o.len = t.byteLength, o.data = t, i != null) {
      let c = Math.floor(i / this.timescale_);
      o.pts = c;
    } else
      o.nearest_pts = this.getNearestTimestampMilliseconds();
    if (s != null) {
      let c = Math.floor(s / this.timescale_);
      o.dts = c;
    }
    this.onPESPrivateData && this.onPESPrivateData(o);
  }
  parseTimedID3MetadataPayload(t, i, s, n, a) {
    let o = new s0();
    if (o.pid = n, o.stream_id = a, o.len = t.byteLength, o.data = t, i != null) {
      let c = Math.floor(i / this.timescale_);
      o.pts = c;
    }
    if (s != null) {
      let c = Math.floor(s / this.timescale_);
      o.dts = c;
    }
    this.onTimedID3Metadata && this.onTimedID3Metadata(o);
  }
  parsePGSPayload(t, i, s, n, a, o) {
    let c = new LA();
    if (c.pid = n, c.lang = o, c.stream_id = a, c.len = t.byteLength, c.data = t, i != null) {
      let l = Math.floor(i / this.timescale_);
      c.pts = l;
    }
    if (s != null) {
      let l = Math.floor(s / this.timescale_);
      c.dts = l;
    }
    this.onPGSSubtitleData && this.onPGSSubtitleData(c);
  }
  parseSynchronousKLVMetadataPayload(t, i, s, n, a) {
    let o = new RA();
    if (o.pid = n, o.stream_id = a, o.len = t.byteLength, o.data = t, i != null) {
      let c = Math.floor(i / this.timescale_);
      o.pts = c;
    }
    if (s != null) {
      let c = Math.floor(s / this.timescale_);
      o.dts = c;
    }
    o.access_units = IA(t), this.onSynchronousKLVMetadata && this.onSynchronousKLVMetadata(o);
  }
  parseAsynchronousKLVMetadataPayload(t, i, s) {
    let n = new s0();
    n.pid = i, n.stream_id = s, n.len = t.byteLength, n.data = t, this.onAsynchronousKLVMetadata && this.onAsynchronousKLVMetadata(n);
  }
  parseSMPTE2038MetadataPayload(t, i, s, n, a) {
    let o = new _A();
    if (o.pid = n, o.stream_id = a, o.len = t.byteLength, o.data = t, i != null) {
      let c = Math.floor(i / this.timescale_);
      o.pts = c;
    }
    if (o.nearest_pts = this.getNearestTimestampMilliseconds(), s != null) {
      let c = Math.floor(s / this.timescale_);
      o.dts = c;
    }
    o.ancillaries = yA(t), this.onSMPTE2038Metadata && this.onSMPTE2038Metadata(o);
  }
  getNearestTimestampMilliseconds() {
    if (this.audio_last_sample_pts_ != null)
      return Math.floor(this.audio_last_sample_pts_);
    if (this.last_pcr_ != null)
      return Math.floor(this.last_pcr_ / 300 / this.timescale_);
  }
  getPcrBase(t) {
    let i = t[6] * 33554432 + t[7] * 131072 + t[8] * 512 + t[9] * 2 + (t[10] & 128) / 128 + this.timestamp_offset_;
    return i + 4294967296 < this.last_pcr_base_ && (i += 8589934592, this.timestamp_offset_ += 8589934592), this.last_pcr_base_ = i, i;
  }
  getTimestamp(t, i) {
    let s = (t[i] & 14) * 536870912 + (t[i + 1] & 255) * 4194304 + (t[i + 2] & 254) * 16384 + (t[i + 3] & 255) * 128 + (t[i + 4] & 254) / 2 + this.timestamp_offset_;
    return s + 4294967296 < this.last_pcr_base_ && (s += 8589934592), s;
  }
}, Is = class F {
  static init() {
    F.types = {
      avc1: [],
      avcC: [],
      btrt: [],
      dinf: [],
      dref: [],
      esds: [],
      ftyp: [],
      hdlr: [],
      hvc1: [],
      hvcC: [],
      av01: [],
      av1C: [],
      mdat: [],
      mdhd: [],
      mdia: [],
      mfhd: [],
      minf: [],
      moof: [],
      moov: [],
      mp4a: [],
      mvex: [],
      mvhd: [],
      sdtp: [],
      stbl: [],
      stco: [],
      stsc: [],
      stsd: [],
      stsz: [],
      stts: [],
      tfdt: [],
      tfhd: [],
      traf: [],
      trak: [],
      trun: [],
      trex: [],
      tkhd: [],
      vmhd: [],
      smhd: [],
      chnl: [],
      ".mp3": [],
      Opus: [],
      dOps: [],
      fLaC: [],
      dfLa: [],
      ipcm: [],
      pcmC: [],
      "ac-3": [],
      dac3: [],
      "ec-3": [],
      dec3: []
    };
    for (let t in F.types)
      F.types.hasOwnProperty(t) && (F.types[t] = [
        t.charCodeAt(0),
        t.charCodeAt(1),
        t.charCodeAt(2),
        t.charCodeAt(3)
      ]);
    let e = F.constants = {};
    e.FTYP = new Uint8Array([
      105,
      115,
      111,
      109,
      // major_brand: isom
      0,
      0,
      0,
      1,
      // minor_version: 0x01
      105,
      115,
      111,
      109,
      // isom
      97,
      118,
      99,
      49
      // avc1
    ]), e.STSD_PREFIX = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      1
      // entry_count
    ]), e.STTS = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0
      // entry_count
    ]), e.STSC = e.STCO = e.STTS, e.STSZ = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // sample_size
      0,
      0,
      0,
      0
      // sample_count
    ]), e.HDLR_VIDEO = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // pre_defined
      118,
      105,
      100,
      101,
      // handler_type: 'vide'
      0,
      0,
      0,
      0,
      // reserved: 3 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      86,
      105,
      100,
      101,
      111,
      72,
      97,
      110,
      100,
      108,
      101,
      114,
      0
      // name: VideoHandler
    ]), e.HDLR_AUDIO = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // pre_defined
      115,
      111,
      117,
      110,
      // handler_type: 'soun'
      0,
      0,
      0,
      0,
      // reserved: 3 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      83,
      111,
      117,
      110,
      100,
      72,
      97,
      110,
      100,
      108,
      101,
      114,
      0
      // name: SoundHandler
    ]), e.DREF = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      1,
      // entry_count
      0,
      0,
      0,
      12,
      // entry_size
      117,
      114,
      108,
      32,
      // type 'url '
      0,
      0,
      0,
      1
      // version(0) + flags
    ]), e.SMHD = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0
      // balance(2) + reserved(2)
    ]), e.VMHD = new Uint8Array([
      0,
      0,
      0,
      1,
      // version(0) + flags
      0,
      0,
      // graphicsmode: 2 bytes
      0,
      0,
      0,
      0,
      // opcolor: 3 * 2 bytes
      0,
      0
    ]);
  }
  // Generate a box
  static box(e) {
    let t = 8, i = null, s = Array.prototype.slice.call(arguments, 1), n = s.length;
    for (let o = 0; o < n; o++)
      t += s[o].byteLength;
    i = new Uint8Array(t), i[0] = t >>> 24 & 255, i[1] = t >>> 16 & 255, i[2] = t >>> 8 & 255, i[3] = t & 255, i.set(e, 4);
    let a = 8;
    for (let o = 0; o < n; o++)
      i.set(s[o], a), a += s[o].byteLength;
    return i;
  }
  // emit ftyp & moov
  static generateInitSegment(e) {
    let t = F.box(F.types.ftyp, F.constants.FTYP), i = F.moov(e), s = new Uint8Array(t.byteLength + i.byteLength);
    return s.set(t, 0), s.set(i, t.byteLength), s;
  }
  // Movie metadata box
  static moov(e) {
    let t = F.mvhd(e.timescale, e.duration), i = F.trak(e), s = F.mvex(e);
    return F.box(F.types.moov, t, i, s);
  }
  // Movie header box
  static mvhd(e, t) {
    return F.box(F.types.mvhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // creation_time
      0,
      0,
      0,
      0,
      // modification_time
      e >>> 24 & 255,
      // timescale: 4 bytes
      e >>> 16 & 255,
      e >>> 8 & 255,
      e & 255,
      t >>> 24 & 255,
      // duration: 4 bytes
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255,
      0,
      1,
      0,
      0,
      // Preferred rate: 1.0
      1,
      0,
      0,
      0,
      // PreferredVolume(1.0, 2bytes) + reserved(2bytes)
      0,
      0,
      0,
      0,
      // reserved: 4 + 4 bytes
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      // ----begin composition matrix----
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      64,
      0,
      0,
      0,
      // ----end composition matrix----
      0,
      0,
      0,
      0,
      // ----begin pre_defined 6 * 4 bytes----
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // ----end pre_defined 6 * 4 bytes----
      255,
      255,
      255,
      255
      // next_track_ID
    ]));
  }
  // Track box
  static trak(e) {
    return F.box(F.types.trak, F.tkhd(e), F.mdia(e));
  }
  // Track header box
  static tkhd(e) {
    let t = e.id, i = e.duration, s = e.presentWidth, n = e.presentHeight;
    return F.box(F.types.tkhd, new Uint8Array([
      0,
      0,
      0,
      7,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // creation_time
      0,
      0,
      0,
      0,
      // modification_time
      t >>> 24 & 255,
      // track_ID: 4 bytes
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255,
      0,
      0,
      0,
      0,
      // reserved: 4 bytes
      i >>> 24 & 255,
      // duration: 4 bytes
      i >>> 16 & 255,
      i >>> 8 & 255,
      i & 255,
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // layer(2bytes) + alternate_group(2bytes)
      0,
      0,
      0,
      0,
      // volume(2bytes) + reserved(2bytes)
      0,
      1,
      0,
      0,
      // ----begin composition matrix----
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      64,
      0,
      0,
      0,
      // ----end composition matrix----
      s >>> 8 & 255,
      // width and height
      s & 255,
      0,
      0,
      n >>> 8 & 255,
      n & 255,
      0,
      0
    ]));
  }
  // Media Box
  static mdia(e) {
    return F.box(F.types.mdia, F.mdhd(e), F.hdlr(e), F.minf(e));
  }
  // Media header box
  static mdhd(e) {
    let t = e.timescale, i = e.duration;
    return F.box(F.types.mdhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      0,
      0,
      0,
      0,
      // creation_time
      0,
      0,
      0,
      0,
      // modification_time
      t >>> 24 & 255,
      // timescale: 4 bytes
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255,
      i >>> 24 & 255,
      // duration: 4 bytes
      i >>> 16 & 255,
      i >>> 8 & 255,
      i & 255,
      85,
      196,
      // language: und (undetermined)
      0,
      0
      // pre_defined = 0
    ]));
  }
  // Media handler reference box
  static hdlr(e) {
    let t = null;
    return e.type === "audio" ? t = F.constants.HDLR_AUDIO : t = F.constants.HDLR_VIDEO, F.box(F.types.hdlr, t);
  }
  // Media infomation box
  static minf(e) {
    let t = null;
    return e.type === "audio" ? t = F.box(F.types.smhd, F.constants.SMHD) : t = F.box(F.types.vmhd, F.constants.VMHD), F.box(F.types.minf, t, F.dinf(), F.stbl(e));
  }
  // Data infomation box
  static dinf() {
    return F.box(
      F.types.dinf,
      F.box(F.types.dref, F.constants.DREF)
    );
  }
  // Sample table box
  static stbl(e) {
    return F.box(
      F.types.stbl,
      // type: stbl
      F.stsd(e),
      // Sample Description Table
      F.box(F.types.stts, F.constants.STTS),
      // Time-To-Sample
      F.box(F.types.stsc, F.constants.STSC),
      // Sample-To-Chunk
      F.box(F.types.stsz, F.constants.STSZ),
      // Sample size
      F.box(F.types.stco, F.constants.STCO)
      // Chunk offset
    );
  }
  // Sample description box
  static stsd(e) {
    return e.type === "audio" ? e.codec === "mp3" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.mp3(e)) : e.codec === "ac-3" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.ac3(e)) : e.codec === "ec-3" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.ec3(e)) : e.codec === "opus" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.Opus(e)) : e.codec == "flac" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.fLaC(e)) : e.codec == "ipcm" ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.ipcm(e)) : F.box(F.types.stsd, F.constants.STSD_PREFIX, F.mp4a(e)) : e.type === "video" && e.codec.startsWith("hvc1") ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.hvc1(e)) : e.type === "video" && e.codec.startsWith("av01") ? F.box(F.types.stsd, F.constants.STSD_PREFIX, F.av01(e)) : F.box(F.types.stsd, F.constants.STSD_PREFIX, F.avc1(e));
  }
  static mp3(e) {
    let t = e.channelCount, i = e.audioSampleRate, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      16,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types[".mp3"], s);
  }
  static mp4a(e) {
    let t = e.channelCount, i = e.audioSampleRate, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      16,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types.mp4a, s, F.esds(e));
  }
  static ac3(e) {
    let t = e.channelCount, i = e.audioSampleRate, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      16,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types["ac-3"], s, F.box(F.types.dac3, new Uint8Array(e.config)));
  }
  static ec3(e) {
    let t = e.channelCount, i = e.audioSampleRate, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      16,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types["ec-3"], s, F.box(F.types.dec3, new Uint8Array(e.config)));
  }
  static esds(e) {
    let t = e.config || [], i = t.length, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // version 0 + flags
      3,
      // descriptor_type
      23 + i,
      // length3
      0,
      1,
      // es_id
      0,
      // stream_priority
      4,
      // descriptor_type
      15 + i,
      // length
      64,
      // codec: mpeg4_audio
      21,
      // stream_type: Audio
      0,
      0,
      0,
      // buffer_size
      0,
      0,
      0,
      0,
      // maxBitrate
      0,
      0,
      0,
      0,
      // avgBitrate
      5
      // descriptor_type
    ].concat([
      i
    ]).concat(
      t
    ).concat([
      6,
      1,
      2
      // GASpecificConfig
    ]));
    return F.box(F.types.esds, s);
  }
  static Opus(e) {
    let t = e.channelCount, i = e.audioSampleRate, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      16,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types.Opus, s, F.dOps(e));
  }
  static dOps(e) {
    let t = e.channelCount, i = e.channelConfigCode, s = e.audioSampleRate;
    if (e.config)
      return F.box(F.types.dOps, e.config);
    let n = [];
    switch (i) {
      case 1:
      case 2:
        n = [0];
        break;
      case 0:
        n = [255, 1, 1, 0, 1];
        break;
      case 128:
        n = [255, 2, 0, 0, 1];
        break;
      case 3:
        n = [1, 2, 1, 0, 2, 1];
        break;
      case 4:
        n = [1, 2, 2, 0, 1, 2, 3];
        break;
      case 5:
        n = [1, 3, 2, 0, 4, 1, 2, 3];
        break;
      case 6:
        n = [1, 4, 2, 0, 4, 1, 2, 3, 5];
        break;
      case 7:
        n = [1, 4, 2, 0, 4, 1, 2, 3, 5, 6];
        break;
      case 8:
        n = [1, 5, 3, 0, 6, 1, 2, 3, 4, 5, 7];
        break;
      case 130:
        n = [1, 1, 2, 0, 1];
        break;
      case 131:
        n = [1, 1, 3, 0, 1, 2];
        break;
      case 132:
        n = [1, 1, 4, 0, 1, 2, 3];
        break;
      case 133:
        n = [1, 1, 5, 0, 1, 2, 3, 4];
        break;
      case 134:
        n = [1, 1, 6, 0, 1, 2, 3, 4, 5];
        break;
      case 135:
        n = [1, 1, 7, 0, 1, 2, 3, 4, 5, 6];
        break;
      case 136:
        n = [1, 1, 8, 0, 1, 2, 3, 4, 5, 6, 7];
        break;
    }
    let a = new Uint8Array([
      0,
      // Version (1)
      t,
      // OutputChannelCount: 2
      0,
      0,
      // PreSkip: 2
      s >>> 24 & 255,
      // Audio sample rate: 4
      s >>> 17 & 255,
      s >>> 8 & 255,
      s >>> 0 & 255,
      0,
      0,
      // Global Gain : 2
      ...n
    ]);
    return F.box(F.types.dOps, a);
  }
  static fLaC(e) {
    let t = e.channelCount, i = Math.min(e.audioSampleRate, 65535), s = e.sampleSize, n = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      s,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return F.box(F.types.fLaC, n, F.dfLa(e));
  }
  static dfLa(e) {
    let t = new Uint8Array([
      0,
      0,
      0,
      0,
      // version, flag
      ...e.config
    ]);
    return F.box(F.types.dfLa, t);
  }
  static ipcm(e) {
    let t = e.channelCount, i = Math.min(e.audioSampleRate, 65535), s = e.sampleSize, n = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // reserved: 2 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      t,
      // channelCount(2)
      0,
      s,
      // sampleSize(2)
      0,
      0,
      0,
      0,
      // reserved(4)
      i >>> 8 & 255,
      // Audio sample rate
      i & 255,
      0,
      0
    ]);
    return e.channelCount === 1 ? F.box(F.types.ipcm, n, F.pcmC(e)) : F.box(F.types.ipcm, n, F.chnl(e), F.pcmC(e));
  }
  static chnl(e) {
    let t = new Uint8Array([
      0,
      0,
      0,
      0,
      // version, flag
      1,
      // Channel Based Layout
      e.channelCount,
      // AudioConfiguration
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
      // omittedChannelsMap
    ]);
    return F.box(F.types.chnl, t);
  }
  static pcmC(e) {
    let t = e.littleEndian ? 1 : 0, i = e.sampleSize, s = new Uint8Array([
      0,
      0,
      0,
      0,
      // version, flag
      t,
      i
    ]);
    return F.box(F.types.pcmC, s);
  }
  static avc1(e) {
    let t = e.avcc, i = e.codecWidth, s = e.codecHeight, n = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // pre_defined(2) + reserved(2)
      0,
      0,
      0,
      0,
      // pre_defined: 3 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      i >>> 8 & 255,
      // width: 2 bytes
      i & 255,
      s >>> 8 & 255,
      // height: 2 bytes
      s & 255,
      0,
      72,
      0,
      0,
      // horizresolution: 4 bytes
      0,
      72,
      0,
      0,
      // vertresolution: 4 bytes
      0,
      0,
      0,
      0,
      // reserved: 4 bytes
      0,
      1,
      // frame_count
      10,
      // strlen
      120,
      113,
      113,
      47,
      // compressorname: 32 bytes
      102,
      108,
      118,
      46,
      106,
      115,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      24,
      // depth
      255,
      255
      // pre_defined = -1
    ]);
    return F.box(F.types.avc1, n, F.box(F.types.avcC, t));
  }
  static hvc1(e) {
    let t = e.hvcc, i = e.codecWidth, s = e.codecHeight, n = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // pre_defined(2) + reserved(2)
      0,
      0,
      0,
      0,
      // pre_defined: 3 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      i >>> 8 & 255,
      // width: 2 bytes
      i & 255,
      s >>> 8 & 255,
      // height: 2 bytes
      s & 255,
      0,
      72,
      0,
      0,
      // horizresolution: 4 bytes
      0,
      72,
      0,
      0,
      // vertresolution: 4 bytes
      0,
      0,
      0,
      0,
      // reserved: 4 bytes
      0,
      1,
      // frame_count
      10,
      // strlen
      120,
      113,
      113,
      47,
      // compressorname: 32 bytes
      102,
      108,
      118,
      46,
      106,
      115,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      24,
      // depth
      255,
      255
      // pre_defined = -1
    ]);
    return F.box(F.types.hvc1, n, F.box(F.types.hvcC, t));
  }
  static av01(e) {
    let t = e.av1c, i = e.codecWidth || 192, s = e.codecHeight || 108, n = new Uint8Array([
      0,
      0,
      0,
      0,
      // reserved(4)
      0,
      0,
      0,
      1,
      // reserved(2) + data_reference_index(2)
      0,
      0,
      0,
      0,
      // pre_defined(2) + reserved(2)
      0,
      0,
      0,
      0,
      // pre_defined: 3 * 4 bytes
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      i >>> 8 & 255,
      // width: 2 bytes
      i & 255,
      s >>> 8 & 255,
      // height: 2 bytes
      s & 255,
      0,
      72,
      0,
      0,
      // horizresolution: 4 bytes
      0,
      72,
      0,
      0,
      // vertresolution: 4 bytes
      0,
      0,
      0,
      0,
      // reserved: 4 bytes
      0,
      1,
      // frame_count
      10,
      // strlen
      120,
      113,
      113,
      47,
      // compressorname: 32 bytes
      102,
      108,
      118,
      46,
      106,
      115,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      24,
      // depth
      255,
      255
      // pre_defined = -1
    ]);
    return F.box(F.types.av01, n, F.box(F.types.av1C, t));
  }
  // Movie Extends box
  static mvex(e) {
    return F.box(F.types.mvex, F.trex(e));
  }
  // Track Extends box
  static trex(e) {
    let t = e.id, i = new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) + flags
      t >>> 24 & 255,
      // track_ID
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255,
      0,
      0,
      0,
      1,
      // default_sample_description_index
      0,
      0,
      0,
      0,
      // default_sample_duration
      0,
      0,
      0,
      0,
      // default_sample_size
      0,
      1,
      0,
      1
      // default_sample_flags
    ]);
    return F.box(F.types.trex, i);
  }
  // Movie fragment box
  static moof(e, t) {
    return F.box(F.types.moof, F.mfhd(e.sequenceNumber), F.traf(e, t));
  }
  static mfhd(e) {
    let t = new Uint8Array([
      0,
      0,
      0,
      0,
      e >>> 24 & 255,
      // sequence_number: int32
      e >>> 16 & 255,
      e >>> 8 & 255,
      e & 255
    ]);
    return F.box(F.types.mfhd, t);
  }
  // Track fragment box
  static traf(e, t) {
    let i = e.id, s = F.box(F.types.tfhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) & flags
      i >>> 24 & 255,
      // track_ID
      i >>> 16 & 255,
      i >>> 8 & 255,
      i & 255
    ])), n = F.box(F.types.tfdt, new Uint8Array([
      0,
      0,
      0,
      0,
      // version(0) & flags
      t >>> 24 & 255,
      // baseMediaDecodeTime: int32
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255
    ])), a = F.sdtp(e), o = F.trun(e, a.byteLength + 16 + 16 + 8 + 16 + 8 + 8);
    return F.box(F.types.traf, s, n, o, a);
  }
  // Sample Dependency Type box
  static sdtp(e) {
    let t = e.samples || [], i = t.length, s = new Uint8Array(4 + i);
    for (let n = 0; n < i; n++) {
      let a = t[n].flags;
      s[n + 4] = a.isLeading << 6 | a.dependsOn << 4 | a.isDependedOn << 2 | a.hasRedundancy;
    }
    return F.box(F.types.sdtp, s);
  }
  // Track fragment run box
  static trun(e, t) {
    let i = e.samples || [], s = i.length, n = 12 + 16 * s, a = new Uint8Array(n);
    t += 8 + n, a.set([
      0,
      0,
      15,
      1,
      // version(0) & flags
      s >>> 24 & 255,
      // sample_count
      s >>> 16 & 255,
      s >>> 8 & 255,
      s & 255,
      t >>> 24 & 255,
      // data_offset
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255
    ], 0);
    for (let o = 0; o < s; o++) {
      let c = i[o].duration, l = i[o].size, d = i[o].flags, h = i[o].cts;
      a.set([
        c >>> 24 & 255,
        // sample_duration
        c >>> 16 & 255,
        c >>> 8 & 255,
        c & 255,
        l >>> 24 & 255,
        // sample_size
        l >>> 16 & 255,
        l >>> 8 & 255,
        l & 255,
        d.isLeading << 2 | d.dependsOn,
        // sample_flags
        d.isDependedOn << 6 | d.hasRedundancy << 4 | d.isNonSync,
        0,
        0,
        // sample_degradation_priority
        h >>> 24 & 255,
        // sample_composition_time_offset
        h >>> 16 & 255,
        h >>> 8 & 255,
        h & 255
      ], 12 + 16 * o);
    }
    return F.box(F.types.trun, a);
  }
  static mdat(e) {
    return F.box(F.types.mdat, e);
  }
};
Is.init();
let df = class {
  static getSilentFrame(e, t) {
    if (e === "mp4a.40.2") {
      if (t === 1)
        return new Uint8Array([0, 200, 0, 128, 35, 128]);
      if (t === 2)
        return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
      if (t === 3)
        return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
      if (t === 4)
        return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
      if (t === 5)
        return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
      if (t === 6)
        return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]);
    } else {
      if (t === 1)
        return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
      if (t === 2)
        return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
      if (t === 3)
        return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
    }
    return null;
  }
};
class Hr {
  constructor(e, t, i, s, n) {
    this.dts = e, this.pts = t, this.duration = i, this.originalDts = s, this.isSyncPoint = n, this.fileposition = null;
  }
}
class hf {
  constructor() {
    this.beginDts = 0, this.endDts = 0, this.beginPts = 0, this.endPts = 0, this.originalBeginDts = 0, this.originalEndDts = 0, this.syncPoints = [], this.firstSample = null, this.lastSample = null;
  }
  appendSyncPoint(e) {
    e.isSyncPoint = !0, this.syncPoints.push(e);
  }
}
class DA {
  constructor() {
    this._list = [];
  }
  clear() {
    this._list = [];
  }
  appendArray(e) {
    let t = this._list;
    e.length !== 0 && (t.length > 0 && e[0].originalDts < t[t.length - 1].originalDts && this.clear(), Array.prototype.push.apply(t, e));
  }
  getLastSyncPointBeforeDts(e) {
    if (this._list.length == 0)
      return null;
    let t = this._list, i = 0, s = t.length - 1, n = 0, a = 0, o = s;
    for (e < t[0].dts && (i = 0, a = o + 1); a <= o; )
      if (n = a + Math.floor((o - a) / 2), n === s || e >= t[n].dts && e < t[n + 1].dts) {
        i = n;
        break;
      } else t[n].dts < e ? a = n + 1 : o = n - 1;
    return this._list[i];
  }
}
class uf {
  constructor(e) {
    this._type = e, this._list = [], this._lastAppendLocation = -1;
  }
  get type() {
    return this._type;
  }
  get length() {
    return this._list.length;
  }
  isEmpty() {
    return this._list.length === 0;
  }
  clear() {
    this._list = [], this._lastAppendLocation = -1;
  }
  _searchNearestSegmentBefore(e) {
    let t = this._list;
    if (t.length === 0)
      return -2;
    let i = t.length - 1, s = 0, n = 0, a = i, o = 0;
    if (e < t[0].originalBeginDts)
      return o = -1, o;
    for (; n <= a; )
      if (s = n + Math.floor((a - n) / 2), s === i || e > t[s].lastSample.originalDts && e < t[s + 1].originalBeginDts) {
        o = s;
        break;
      } else t[s].originalBeginDts < e ? n = s + 1 : a = s - 1;
    return o;
  }
  _searchNearestSegmentAfter(e) {
    return this._searchNearestSegmentBefore(e) + 1;
  }
  append(e) {
    let t = this._list, i = e, s = this._lastAppendLocation, n = 0;
    s !== -1 && s < t.length && i.originalBeginDts >= t[s].lastSample.originalDts && (s === t.length - 1 || s < t.length - 1 && i.originalBeginDts < t[s + 1].originalBeginDts) ? n = s + 1 : t.length > 0 && (n = this._searchNearestSegmentBefore(i.originalBeginDts) + 1), this._lastAppendLocation = n, this._list.splice(n, 0, i);
  }
  getLastSegmentBefore(e) {
    let t = this._searchNearestSegmentBefore(e);
    return t >= 0 ? this._list[t] : null;
  }
  getLastSampleBefore(e) {
    let t = this.getLastSegmentBefore(e);
    return t != null ? t.lastSample : null;
  }
  getLastSyncPointBefore(e) {
    let t = this._searchNearestSegmentBefore(e), i = this._list[t].syncPoints;
    for (; i.length === 0 && t > 0; )
      t--, i = this._list[t].syncPoints;
    return i.length > 0 ? i[i.length - 1] : null;
  }
}
let r0 = class {
  constructor(e) {
    this.TAG = S.traceTag("MP4Remuxer", e.traceId), this._config = e, this._isLive = e.isLive === !0, this._dtsBase = -1, this._dtsBaseInited = !1, this._audioDtsBase = 1 / 0, this._videoDtsBase = 1 / 0, this._audioNextDts = void 0, this._videoNextDts = void 0, this._audioStashedLastSample = null, this._videoStashedLastSample = null, this._audioMeta = null, this._videoMeta = null, this._audioSegmentInfoList = new uf("audio"), this._videoSegmentInfoList = new uf("video"), this._onInitSegment = null, this._onMediaSegment = null, this._forceFirstIDR = !!(ye.chrome && (ye.version.major < 50 || ye.version.major === 50 && ye.version.build < 2661)), this._fillSilentAfterSeek = ye.msedge || ye.msie, this._mp3UseMpegAudio = !ye.firefox, this._fillAudioTimestampGap = this._config.fixAudioTimestampGap;
  }
  destroy() {
    this._dtsBase = -1, this._dtsBaseInited = !1, this._audioMeta = null, this._videoMeta = null, this._audioSegmentInfoList.clear(), this._audioSegmentInfoList = null, this._videoSegmentInfoList.clear(), this._videoSegmentInfoList = null, this._onInitSegment = null, this._onMediaSegment = null;
  }
  bindDataSource(e) {
    return e.onDataAvailable = this.remux.bind(this), e.onTrackMetadata = this._onTrackMetadataReceived.bind(this), this;
  }
  /* prototype: function onInitSegment(type: string, initSegment: ArrayBuffer): void
     InitSegment: {
         type: string,
         data: ArrayBuffer,
         codec: string,
         container: string
     }
  */
  get onInitSegment() {
    return this._onInitSegment;
  }
  set onInitSegment(e) {
    this._onInitSegment = e;
  }
  /* prototype: function onMediaSegment(type: string, mediaSegment: MediaSegment): void
     MediaSegment: {
         type: string,
         data: ArrayBuffer,
         sampleCount: int32
         info: MediaSegmentInfo
     }
  */
  get onMediaSegment() {
    return this._onMediaSegment;
  }
  set onMediaSegment(e) {
    this._onMediaSegment = e;
  }
  insertDiscontinuity() {
    this._audioNextDts = this._videoNextDts = void 0;
  }
  seek(e) {
    this._audioStashedLastSample = null, this._videoStashedLastSample = null, this._videoSegmentInfoList.clear(), this._audioSegmentInfoList.clear();
  }
  remux(e, t) {
    if (!this._onMediaSegment)
      throw new qe("MP4Remuxer: onMediaSegment callback must be specificed!");
    this._dtsBaseInited || this._calculateDtsBase(e, t), t && this._remuxVideo(t), e && this._remuxAudio(e);
  }
  _onTrackMetadataReceived(e, t) {
    let i = null, s = "mp4", n = t.codec;
    if (e === "audio")
      this._audioMeta = t, t.codec === "mp3" && this._mp3UseMpegAudio ? (s = "mpeg", n = "", i = new Uint8Array()) : i = Is.generateInitSegment(t);
    else if (e === "video")
      this._videoMeta = t, i = Is.generateInitSegment(t);
    else
      return;
    if (!this._onInitSegment)
      throw new qe("MP4Remuxer: onInitSegment callback must be specified!");
    this._onInitSegment(e, {
      type: e,
      data: i.buffer,
      codec: n,
      container: `${e}/${s}`,
      mediaDuration: t.duration
      // in timescale 1000 (milliseconds)
    });
  }
  _calculateDtsBase(e, t) {
    this._dtsBaseInited || (e && e.samples && e.samples.length && (this._audioDtsBase = e.samples[0].dts), t && t.samples && t.samples.length && (this._videoDtsBase = t.samples[0].dts), this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase), this._dtsBaseInited = !0);
  }
  getTimestampBase() {
    if (this._dtsBaseInited)
      return this._dtsBase;
  }
  flushStashedSamples() {
    let e = this._videoStashedLastSample, t = this._audioStashedLastSample, i = {
      type: "video",
      id: 1,
      sequenceNumber: 0,
      samples: [],
      length: 0
    };
    e != null && (i.samples.push(e), i.length = e.length);
    let s = {
      type: "audio",
      id: 2,
      sequenceNumber: 0,
      samples: [],
      length: 0
    };
    t != null && (s.samples.push(t), s.length = t.length), this._videoStashedLastSample = null, this._audioStashedLastSample = null, this._remuxVideo(i, !0), this._remuxAudio(s, !0);
  }
  _remuxAudio(e, t) {
    if (this._audioMeta == null)
      return;
    let i = e, s = i.samples, n, a = -1, o = -1, c = this._audioMeta.refSampleDuration, l = this._audioMeta.codec === "mp3" && this._mp3UseMpegAudio, d = this._dtsBaseInited && this._audioNextDts === void 0, h = !1;
    if (!s || s.length === 0 || s.length === 1 && !t)
      return;
    let u = 0, f = null, p = 0;
    l ? (u = 0, p = i.length) : (u = 8, p = 8 + i.length);
    let m = null;
    if (s.length > 1 && (m = s.pop(), p -= m.length), this._audioStashedLastSample != null) {
      let A = this._audioStashedLastSample;
      this._audioStashedLastSample = null, s.unshift(A), p += A.length;
    }
    m != null && (this._audioStashedLastSample = m);
    let g = s[0].dts - this._dtsBase;
    if (this._audioNextDts)
      n = g - this._audioNextDts;
    else if (this._audioSegmentInfoList.isEmpty())
      n = 0, this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty() && this._audioMeta.originalCodec !== "mp3" && (h = !0);
    else {
      let A = this._audioSegmentInfoList.getLastSampleBefore(g);
      if (A != null) {
        let C = g - (A.originalDts + A.duration);
        C <= 3 && (C = 0);
        let I = A.dts + A.duration + C;
        n = g - I;
      } else
        n = 0;
    }
    if (h) {
      let A = g - n, C = this._videoSegmentInfoList.getLastSegmentBefore(g);
      if (C != null && C.beginDts < A) {
        let I = df.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
        if (I) {
          let L = C.beginDts, R = A - C.beginDts;
          S.v(this.TAG, `InsertPrefixSilentAudio: dts: ${L}, duration: ${R}`), s.unshift({ unit: I, dts: L, pts: L }), p += I.byteLength;
        }
      } else
        h = !1;
    }
    let x = [];
    for (let A = 0; A < s.length; A++) {
      let C = s[A], I = C.unit, L = C.dts - this._dtsBase, R = L, D = !1, M = null, w = 0;
      if (!(L < -1e-3)) {
        if (this._audioMeta.codec !== "mp3" && c != null) {
          let N = L;
          const H = 3;
          if (this._audioNextDts && (N = this._audioNextDts), n = L - N, n <= -H * c) {
            S.w(this.TAG, `Dropping 1 audio frame (originalDts: ${L} ms ,curRefDts: ${N} ms)  due to dtsCorrection: ${n} ms overlap.`);
            continue;
          } else if (n >= H * c && this._fillAudioTimestampGap && !ye.safari) {
            D = !0;
            let G = Math.floor(n / c);
            S.w(this.TAG, `Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.
originalDts: ${L} ms, curRefDts: ${N} ms, dtsCorrection: ${Math.round(n)} ms, generate: ${G} frames`), R = Math.floor(N), w = Math.floor(N + c) - R;
            let Z = df.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount);
            Z == null && (S.w(this.TAG, `Unable to generate silent frame for ${this._audioMeta.originalCodec} with ${this._audioMeta.channelCount} channels, repeat last frame`), Z = I), M = [];
            for (let $ = 0; $ < G; $++) {
              N = N + c;
              let Y = Math.floor(N), W = Math.floor(N + c) - Y, k = {
                dts: Y,
                pts: Y,
                cts: 0,
                unit: Z,
                size: Z.byteLength,
                duration: W,
                // wait for next sample
                originalDts: L,
                flags: {
                  isLeading: 0,
                  dependsOn: 1,
                  isDependedOn: 0,
                  hasRedundancy: 0
                }
              };
              M.push(k), p += k.size;
            }
            this._audioNextDts = N + c;
          } else
            R = Math.floor(N), w = Math.floor(N + c) - R, this._audioNextDts = N + c;
        } else
          R = L - n, A !== s.length - 1 ? w = s[A + 1].dts - this._dtsBase - n - R : m != null ? w = m.dts - this._dtsBase - n - R : x.length >= 1 ? w = x[x.length - 1].duration : w = Math.floor(c), this._audioNextDts = R + w;
        a === -1 && (a = R), x.push({
          dts: R,
          pts: R,
          cts: 0,
          unit: C.unit,
          size: C.unit.byteLength,
          duration: w,
          originalDts: L,
          flags: {
            isLeading: 0,
            dependsOn: 1,
            isDependedOn: 0,
            hasRedundancy: 0
          }
        }), D && x.push.apply(x, M);
      }
    }
    if (x.length === 0) {
      i.samples = [], i.length = 0;
      return;
    }
    l ? f = new Uint8Array(p) : (f = new Uint8Array(p), f[0] = p >>> 24 & 255, f[1] = p >>> 16 & 255, f[2] = p >>> 8 & 255, f[3] = p & 255, f.set(Is.types.mdat, 4));
    for (let A = 0; A < x.length; A++) {
      let C = x[A].unit;
      f.set(C, u), u += C.byteLength;
    }
    let _ = x[x.length - 1];
    o = _.dts + _.duration;
    let v = new hf();
    v.beginDts = a, v.endDts = o, v.beginPts = a, v.endPts = o, v.originalBeginDts = x[0].originalDts, v.originalEndDts = _.originalDts + _.duration, v.firstSample = new Hr(
      x[0].dts,
      x[0].pts,
      x[0].duration,
      x[0].originalDts,
      !1
    ), v.lastSample = new Hr(
      _.dts,
      _.pts,
      _.duration,
      _.originalDts,
      !1
    ), this._isLive || this._audioSegmentInfoList.append(v), i.samples = x, i.sequenceNumber++;
    let E = null;
    l ? E = new Uint8Array() : E = Is.moof(i, a), i.samples = [], i.length = 0;
    let b = {
      type: "audio",
      data: this._mergeBoxes(E, f).buffer,
      sampleCount: x.length,
      info: v
    };
    l && d && (b.timestampOffset = a), this._onMediaSegment("audio", b);
  }
  _remuxVideo(e, t) {
    if (this._videoMeta == null)
      return;
    let i = e, s = i.samples, n, a = -1, o = -1, c = -1, l = -1;
    if (!s || s.length === 0 || s.length === 1 && !t)
      return;
    let d = 8, h = null, u = 8 + e.length, f = null;
    if (s.length > 1 && (f = s.pop(), u -= f.length), this._videoStashedLastSample != null) {
      let v = this._videoStashedLastSample;
      this._videoStashedLastSample = null, s.unshift(v), u += v.length;
    }
    f != null && (this._videoStashedLastSample = f);
    let p = s[0].dts - this._dtsBase;
    if (this._videoNextDts)
      n = p - this._videoNextDts;
    else if (this._videoSegmentInfoList.isEmpty())
      n = 0;
    else {
      let v = this._videoSegmentInfoList.getLastSampleBefore(p);
      if (v != null) {
        let E = p - (v.originalDts + v.duration);
        E <= 3 && (E = 0);
        let b = v.dts + v.duration + E;
        n = p - b;
      } else
        n = 0;
    }
    let m = new hf(), g = [];
    for (let v = 0; v < s.length; v++) {
      let E = s[v], b = E.dts - this._dtsBase, A = E.isKeyframe, C = b - n, I = E.cts, L = C + I;
      a === -1 && (a = C, c = L);
      let R = 0;
      if (v !== s.length - 1 ? R = s[v + 1].dts - this._dtsBase - n - C : f != null ? R = f.dts - this._dtsBase - n - C : g.length >= 1 ? R = g[g.length - 1].duration : R = Math.floor(this._videoMeta.refSampleDuration), A) {
        let D = new Hr(C, L, R, E.dts, !0);
        D.fileposition = E.fileposition, m.appendSyncPoint(D);
      }
      g.push({
        dts: C,
        pts: L,
        cts: I,
        units: E.units,
        size: E.length,
        isKeyframe: A,
        duration: R,
        originalDts: b,
        flags: {
          isLeading: 0,
          dependsOn: A ? 2 : 1,
          isDependedOn: A ? 1 : 0,
          hasRedundancy: 0,
          isNonSync: A ? 0 : 1
        }
      });
    }
    h = new Uint8Array(u), h[0] = u >>> 24 & 255, h[1] = u >>> 16 & 255, h[2] = u >>> 8 & 255, h[3] = u & 255, h.set(Is.types.mdat, 4);
    for (let v = 0; v < g.length; v++) {
      let E = g[v].units;
      for (; E.length; ) {
        let A = E.shift().data;
        h.set(A, d), d += A.byteLength;
      }
    }
    let x = g[g.length - 1];
    if (o = x.dts + x.duration, l = x.pts + x.duration, this._videoNextDts = o, m.beginDts = a, m.endDts = o, m.beginPts = c, m.endPts = l, m.originalBeginDts = g[0].originalDts, m.originalEndDts = x.originalDts + x.duration, m.firstSample = new Hr(
      g[0].dts,
      g[0].pts,
      g[0].duration,
      g[0].originalDts,
      g[0].isKeyframe
    ), m.lastSample = new Hr(
      x.dts,
      x.pts,
      x.duration,
      x.originalDts,
      x.isKeyframe
    ), this._isLive || this._videoSegmentInfoList.append(m), i.samples = g, i.sequenceNumber++, this._forceFirstIDR) {
      let v = g[0].flags;
      v.dependsOn = 2, v.isNonSync = 0;
    }
    let _ = Is.moof(i, a);
    i.samples = [], i.length = 0, this._onMediaSegment("video", {
      type: "video",
      data: this._mergeBoxes(_, h).buffer,
      sampleCount: g.length,
      info: m
    });
  }
  _mergeBoxes(e, t) {
    let i = new Uint8Array(e.byteLength + t.byteLength);
    return i.set(e, 0), i.set(t, e.byteLength), i;
  }
};
var X = /* @__PURE__ */ ((r) => (r.IO_ERROR = "io_error", r.DEMUX_ERROR = "demux_error", r.INIT_SEGMENT = "init_segment", r.MEDIA_SEGMENT = "media_segment", r.LOADING_COMPLETE = "loading_complete", r.RECOVERED_EARLY_EOF = "recovered_early_eof", r.MEDIA_INFO = "media_info", r.METADATA_ARRIVED = "metadata_arrived", r.SCRIPTDATA_ARRIVED = "scriptdata_arrived", r.TIMED_ID3_METADATA_ARRIVED = "timed_id3_metadata_arrived", r.PGS_SUBTITLE_ARRIVED = "pgs_subtitle_arrived", r.SYNCHRONOUS_KLV_METADATA_ARRIVED = "synchronous_klv_metadata_arrived", r.ASYNCHRONOUS_KLV_METADATA_ARRIVED = "asynchronous_klv_metadata_arrived", r.SMPTE2038_METADATA_ARRIVED = "smpte2038_metadata_arrived", r.SCTE35_METADATA_ARRIVED = "scte35_metadata_arrived", r.PES_PRIVATE_DATA_DESCRIPTOR = "pes_private_data_descriptor", r.PES_PRIVATE_DATA_ARRIVED = "pes_private_data_arrived", r.STATISTICS_INFO = "statistics_info", r.RECOMMEND_SEEKPOINT = "recommend_seekpoint", r.LOADED_COMPATIBLE_VIDEO = "LOADED_COMPATIBLE_VIDEO", r.LOADED_COMPATIBLE_AUDIO = "LOADED_COMPATIBLE_AUDIO", r.NO_DATA_RECEIVED = "NO_DATA_RECEIVED", r.CUSTOM_TRANSLATE_MESSAGE = "CUSTOM_TRANSLATE_MESSAGE", r))(X || {});
const ff = new Uint8Array([0, 0, 0, 1]), Kn = {
  dts: 0,
  base: 0,
  start: -1,
  last: -1,
  gap: 0,
  cnt: 0
}, Zr = {
  id: 101,
  type: jt.Video,
  samples: [],
  length: 0,
  sequenceNumber: 0
}, Xn = {
  id: 101,
  type: jt.Audio,
  samples: [],
  length: 0,
  sequenceNumber: 0
};
class n0 {
  constructor(e) {
    y(this, "TAG");
    y(this, "config");
    y(this, "isDestroyed", !1);
    y(this, "dtsBaseInited", !1);
    y(this, "needBufferData", !1);
    y(this, "compatibleVideoTrack", {
      ...Zr,
      samples: []
    });
    y(this, "compatibleAudioTrack", {
      ...Xn,
      samples: []
    });
    y(this, "calcInfo", {
      video: { ...Kn },
      audio: { ...Kn }
    });
    y(this, "meidaCache", {
      video: {
        ...Zr,
        samples: [],
        id: -1
      },
      audio: {
        ...Xn,
        samples: [],
        id: -1
      }
    });
    y(this, "firstAudioTS", -1);
    y(this, "firstVideoTS", -1);
    y(this, "audioMeta");
    y(this, "videoMeta");
    y(this, "onCompatibleVideo");
    y(this, "onCompatibleAudio");
    y(this, "onNoDataReceived");
    y(this, "onTrackMetadata");
    y(this, "onDataAvailable");
    y(this, "noDataReceivedTimer");
    this.TAG = S.traceTag("MediaBridge", e.traceId), this.config = e, this.destroy(!1), this.watchNoDataReceived();
  }
  destroy(e = !0) {
    this.isDestroyed = e, this.stopWatchNoDataReceived(), this.dtsBaseInited = !1, this.needBufferData = !0, this.compatibleVideoTrack = {
      ...Zr,
      samples: []
    }, this.compatibleAudioTrack = {
      ...Xn,
      samples: []
    }, this.calcInfo = {
      video: { ...Kn },
      audio: { ...Kn }
    }, this.meidaCache = {
      video: {
        ...Zr,
        samples: [],
        id: -1
      },
      audio: {
        ...Xn,
        samples: [],
        id: -1
      }
    }, this.firstAudioTS = -1, this.firstVideoTS = -1;
  }
  bindDataSource(e) {
    return e.onDataAvailable = this.remux.bind(this), e.onTrackMetadata = (t, i) => {
      var s;
      t === jt.Audio && (this.audioMeta = i), t === jt.Video && (this.videoMeta = i), (s = this.onTrackMetadata) == null || s.call(this, t, i);
    }, e.onCompatibleVideo = this.remuxCompatibleVideo.bind(this), e.onCompatibleAudio = this.remuxCompatibleAudio.bind(this), this;
  }
  hungry(e = 500) {
    const t = this.config;
    let { liveBufferMS: i = 0, liveBufferMaxMS: s = 4e3, liveBufferMinMS: n = 150 } = t;
    i += e, t.liveBufferMS = Math.max(n, Math.min(s, i)), e > 0 && (this.needBufferData = !0, S.w(this.TAG, `player hungry! buffer ms:${t.liveBufferMS} delta=${e}`));
  }
  /**
   * 缓存数据
   * @param {*} audioTrack
   * @param {*} videoTrack
   */
  toCacheMeidaData(e, t) {
    const { video: i, audio: s } = this.meidaCache, n = t.samples || [], a = e.samples || [];
    n.length && (i.samples.push(...n), i.id = t.id, i.length += t.length, this.resetTrack(t)), a.length && (s.samples.push(...a), s.id = e.id, s.length += e.length, this.resetTrack(e));
  }
  /**
   * 检测是否需要缓存
   * @returns
   */
  checkNeedCacheData() {
    let { liveBufferMS: e = 0 } = this.config;
    if (e <= 0 || !this.needBufferData) return !1;
    let t = this.audioMeta, i = this.videoMeta;
    if (!this.dtsBaseInited || this.needBufferData) {
      const { video: s, audio: n } = this.meidaCache, a = s.samples, o = n.samples, c = a.length, l = o.length;
      if (i) {
        if (!c) return !0;
        const d = a[c - 1].dts - a[0].dts;
        if (d >= 0 && d < e && c < 40) return !0;
      }
      if (t) {
        if (!l) return !0;
        const d = o[l - 1].dts - o[0].dts;
        if (d >= 0 && d < e && l < 40) return !0;
      }
    }
    return this.needBufferData = !1, !1;
  }
  /**
   * 一定时间内没有收到数据，做超时处理
   * @returns
   */
  watchNoDataReceived() {
    this.stopWatchNoDataReceived();
    let { bufferWaitTimeMS: e } = this.config;
    this.noDataReceivedTimer = setTimeout(() => {
      var t;
      S.e(this.TAG, "Long time no data received"), (t = this.onNoDataReceived) == null || t.call(this);
    }, e);
  }
  stopWatchNoDataReceived() {
    clearTimeout(this.noDataReceivedTimer);
  }
  groupTrackByStreamId(e) {
    const { samples: t = [], type: i, id: s } = e, n = { ...Zr, type: i, id: s, samples: [] };
    return t.forEach((a) => {
      n.samples.push(a);
    }), { 0: n };
  }
  remux(e, t) {
    if (this.isDestroyed) {
      this.resetTrack(t), this.resetTrack(e);
      return;
    }
    this.dtsBaseInited || (this.dtsBaseInited = !0);
    let i = t.samples || [], s = e.samples || [], n = this.firstVideoTS;
    i.length && n === -1 && (n = this.firstVideoTS = i[0].dts, S.k(this.TAG, `received video first dts = ${n}`));
    let a = this.firstAudioTS;
    s.length && a === -1 && (a = this.firstAudioTS = s[0].dts, S.k(this.TAG, `received audio first dts = ${a}`));
    const o = this.groupTrackByStreamId(t);
    if (Object.values(o).forEach((u) => {
      this.correctDts(u);
    }), this.correctDts(e), this.checkNeedCacheData()) {
      this.toCacheMeidaData(e, t);
      return;
    }
    this.watchNoDataReceived();
    const { video: c, audio: l } = this.meidaCache;
    if (c.samples.length && t.id === c.id && (i = t.samples = c.samples.concat(t.samples), t.length += c.length, this.resetTrack(c), c.id = -1), l.samples.length && e.id === l.id && (s = e.samples = l.samples.concat(e.samples), e.length += l.length, this.resetTrack(l), l.id = -1), e.id === this.compatibleAudioTrack.id && (e.samples.forEach((u) => {
      var f;
      return (f = this.onCompatibleAudio) == null ? void 0 : f.call(this, u);
    }), this.resetTrack(e), s = []), t.id === this.compatibleVideoTrack.id && (t.samples.forEach((u) => {
      var E;
      const { isStaticFrame: f, units: p, dts: m, isKeyframe: g, videoMeta: x, ipcamTime: _ } = u;
      let v;
      if (p != null && p.length && (xc(this.videoMeta.codec) === de.H265 ? v = this.parseH265Video(g, p) : v = this.parseH264Video(g, p)), v) {
        const b = {
          isStaticFrame: f,
          unit: v,
          dts: m,
          isKeyframe: g,
          videoMeta: x,
          ipcamTime: _
        };
        (E = this.onCompatibleVideo) == null || E.call(this, b);
      }
    }), this.resetTrack(t), i = []), s.length || i.length) {
      const u = this.groupTrackByStreamId(t);
      Object.values(u).forEach((f) => {
        var p;
        f.length = f.samples.reduce((m, g, x) => m + g.length, 0), f.sequenceNumber = t.sequenceNumber, (p = this.onDataAvailable) == null || p.call(this, e, f), this.toCacheMeidaData(e, f), t.sequenceNumber = f.sequenceNumber, this.resetTrack(t);
      });
    }
  }
  resetTrack(e) {
    e.samples = [], e.length = 0;
  }
  correctDts(e) {
    let { type: t, samples: i } = e;
    if (!(i != null && i.length)) return;
    const s = this.calcInfo[t];
    let { dts: n, base: a, start: o, last: c, gap: l, cnt: d } = s;
    i.forEach((h) => {
      let { dts: u, isStaticFrame: f, corrected: p = !1 } = h;
      if (!p) {
        if (o === -1)
          o = u;
        else {
          const m = u - c, g = t === "video" ? 110 : 200;
          m > 10 && m < g && !f && (l += m, d++);
          const x = m > Zt;
          if ((m < 0 || x) && (S.w(this.TAG, `[${t}] dts wrong  dts=${u} last=${c}. current dts = ${n}`), !f || !x)) {
            o = u;
            let _ = 40;
            d !== 0 && (_ = Math.round(l / d)), m > 0 && (_ = Math.min(_, m)), a = n + _;
          }
        }
        n = a + u - o, h.dts = h.pts = n, h.corrected = !0, c = u;
      }
    }), Object.assign(s, { dts: n, base: a, start: o, last: c, gap: l, cnt: d });
  }
  remuxCompatibleVideo(e) {
    var n;
    const { units: t, videoMeta: i } = e;
    i && (this.videoMeta = i);
    const s = t == null ? void 0 : t.map((a) => {
      let o = a.data.slice(4);
      return wm(o, ff) || (o = ui(ff, o)), a.data = o, a;
    });
    (n = this.remuxCompatible) == null || n.call(
      this,
      {
        ...e,
        units: s
      },
      this.compatibleVideoTrack
    );
  }
  parseH265Video(e, t) {
    if (!t.length) return;
    const i = [], s = [];
    if (t.forEach((n) => {
      let { type: a, data: o } = n;
      a < 22 ? (e && s.push(...i), s.push(o)) : [32, 33, 34].includes(a) && i.push(o);
    }), !!s.length)
      return ui(...s).buffer;
  }
  parseH264Video(e, t) {
    if (!t.length) return;
    const i = [], s = [];
    if (t.forEach((n) => {
      let { type: a, data: o } = n;
      [zt.kSliceIDR, zt.kSliceNonIDR].includes(a) ? (e && s.push(...i), s.push(o)) : [zt.kSliceSPS, zt.kSlicePPS].includes(a) && i.push(o);
    }), !!s.length)
      return ui(...s).buffer;
  }
  remuxCompatibleAudio(e) {
    this.remuxCompatible(e, this.compatibleAudioTrack);
  }
  remuxCompatible(e, t) {
    t.samples.push(e), this.remux(this.compatibleAudioTrack, this.compatibleVideoTrack);
  }
  /**
   *
   * SEI解析
   * http://www.ciotimes.com/IT/145001.html
   *
   * @param {*} dataBuffer
   * @returns
   */
  // private parseVideoSEI(dataBuffer: Uint8Array) {
  //     const UUID_SIZE = 16;
  //     let seiType = 0;
  //     let seiTypeCount = 0;
  //     let seiSize = 0;
  //     let seiSizeCount = 0;
  //     let offset = 0;
  //     let dataSize = dataBuffer.byteLength;
  //     //payload type
  //     do {
  //         seiType += dataBuffer[offset];
  //         seiTypeCount++;
  //     } while (dataBuffer[++offset] == 255);
  //     //payload size
  //     do {
  //         seiSize += dataBuffer[offset];
  //         seiSizeCount++;
  //     } while (dataBuffer[++offset] == 255);
  //     let seiContentCount = dataSize - seiSizeCount - seiTypeCount;
  //     //check UUID
  //     let uuid = dataBuffer.slice(offset, offset + UUID_SIZE).toString();
  //     let seiBuffer = new Uint8Array(seiContentCount),
  //         usedBytes = 0;
  //     if (seiSize >= UUID_SIZE && seiSize <= seiContentCount && seiType == 5 && uuid === SEI_FACE_INFO_UUID) {
  //         offset += UUID_SIZE;
  //         seiSize -= UUID_SIZE;
  //         let p = offset,
  //             end = offset + seiContentCount - UUID_SIZE - 3;
  //         for (; p < end; ) {
  //             if (dataBuffer.slice(p, p + 3).toString() === '0,0,3') {
  //                 seiBuffer.set(dataBuffer.slice(p, p + 2), usedBytes);
  //                 usedBytes += 2;
  //                 p += 3;
  //             } else {
  //                 seiBuffer.set([dataBuffer[p++]], usedBytes++);
  //             }
  //         }
  //         let leftSize = offset + seiContentCount - UUID_SIZE - p;
  //         if (leftSize > 0) {
  //             seiBuffer.set(dataBuffer.slice(p, p + leftSize), usedBytes);
  //             usedBytes += leftSize;
  //         }
  //     }
  //     let result = {
  //         type: seiType,
  //         buffer: seiBuffer.slice(0, seiSize),
  //         size: seiSize,
  //     };
  //     return result;
  // }
}
class pf {
  constructor(e, t) {
    y(this, "_onCompatibleVideo", (e) => {
      var t;
      (t = this._emitter) == null || t.emit(X.LOADED_COMPATIBLE_VIDEO, e);
    });
    y(this, "_onCompatibleAudio", (e) => {
      var t;
      (t = this._emitter) == null || t.emit(X.LOADED_COMPATIBLE_AUDIO, e);
    });
    y(this, "_onNoDataReceived", () => {
      var e;
      (e = this._emitter) == null || e.emit(X.NO_DATA_RECEIVED);
    });
    this.TAG = S.traceTag("TransmuxingController", t.traceId), this._emitter = new ve(), this._emitter.setMaxListeners(100), this._config = t, e.segments || (e.segments = [{
      duration: e.duration,
      filesize: e.filesize,
      url: e.url,
      extraOptions: e.extraOptions,
      type: e.type
    }]), typeof e.cors != "boolean" && (e.cors = !0), typeof e.withCredentials != "boolean" && (e.withCredentials = !1), this._mediaDataSource = e, this._currentSegmentIndex = 0;
    let i = 0;
    this._mediaDataSource.segments.forEach((s) => {
      s.timestampBase = i, i += s.duration, s.cors = e.cors, s.withCredentials = e.withCredentials, t.referrerPolicy && (s.referrerPolicy = t.referrerPolicy);
    }), !isNaN(i) && this._mediaDataSource.duration !== i && (this._mediaDataSource.duration = i), this._mediaInfo = null, this._demuxer = null, this._remuxer = null, this._ioctl = null, this._pendingSeekTime = null, this._pendingResolveSeekPoint = null, this._statisticsReporter = null;
  }
  destroy() {
    this._mediaInfo = null, this._mediaDataSource = null, this._statisticsReporter && this._disableStatisticsReporter(), this._ioctl && (this._ioctl.destroy(), this._ioctl = null), this._demuxer && (this._demuxer.destroy(), this._demuxer = null), this._remuxer && (this._remuxer.destroy(), this._remuxer = null), this._mediaBridge && (this._mediaBridge.destroy(), this._mediaBridge = null), this._emitter.removeAllListeners(), this._emitter = null;
  }
  on(e, t) {
    this._emitter.addListener(e, t);
  }
  off(e, t) {
    this._emitter.removeListener(e, t);
  }
  start() {
    this._loadSegment(0), this._enableStatisticsReporter();
  }
  _loadSegment(e, t) {
    this._currentSegmentIndex = e;
    let i = this._mediaDataSource.segments[e], s = this._ioctl = new vc(i, this._config, e);
    s.onError = this._onIOException.bind(this), s.onSeeked = this._onIOSeeked.bind(this), s.onComplete = this._onIOComplete.bind(this), s.onRedirect = this._onIORedirect.bind(this), s.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this), t ? this._demuxer.bindDataSource(this._ioctl) : s.onDataArrival = this._onInitChunkArrival.bind(this), s.open(t);
  }
  stop() {
    this._internalAbort(), this._disableStatisticsReporter();
  }
  _internalAbort() {
    this._ioctl && (this._ioctl.destroy(), this._ioctl = null);
  }
  pause() {
    this._ioctl && this._ioctl.isWorking() && (this._ioctl.pause(), this._disableStatisticsReporter());
  }
  resume() {
    this._ioctl && this._ioctl.isPaused() && (this._ioctl.resume(), this._enableStatisticsReporter());
  }
  seek(e) {
    if (this._mediaInfo == null || !this._mediaInfo.isSeekable())
      return;
    let t = this._searchSegmentIndexContains(e);
    if (t === this._currentSegmentIndex) {
      let i = this._mediaInfo.segments[t];
      if (i == null)
        this._pendingSeekTime = e;
      else {
        let s = i.getNearestKeyframe(e);
        this._remuxer.seek(s.milliseconds), this._ioctl.seek(s.fileposition), this._pendingResolveSeekPoint = s.milliseconds;
      }
    } else {
      let i = this._mediaInfo.segments[t];
      if (i == null)
        this._pendingSeekTime = e, this._internalAbort(), this._remuxer.seek(), this._remuxer.insertDiscontinuity(), this._loadSegment(t);
      else {
        let s = i.getNearestKeyframe(e);
        this._internalAbort(), this._remuxer.seek(e), this._remuxer.insertDiscontinuity(), this._demuxer.resetMediaInfo(), this._demuxer.timestampBase = this._mediaDataSource.segments[t].timestampBase, this._loadSegment(t, s.fileposition), this._pendingResolveSeekPoint = s.milliseconds, this._reportSegmentMediaInfo(t);
      }
    }
    this._enableStatisticsReporter();
  }
  hungry(e) {
    var t;
    (t = this._mediaBridge) == null || t.hungry(e);
  }
  setPlayTactics(e) {
    var t, i;
    (i = (t = this._demuxer) == null ? void 0 : t.setPlayTactics) == null || i.call(t, e);
  }
  _searchSegmentIndexContains(e) {
    let t = this._mediaDataSource.segments, i = t.length - 1;
    for (let s = 0; s < t.length; s++)
      if (e < t[s].timestampBase) {
        i = s - 1;
        break;
      }
    return i;
  }
  _onInitChunkArrival(e, t) {
    let i = 0;
    const { type: s, hasAudio: n, hasVideo: a, duration: o, segments: c } = this._mediaDataSource;
    if (t > 0 && (this._demuxer.bindDataSource(this._ioctl), this._demuxer.timestampBase = c[this._currentSegmentIndex].timestampBase, i = this._demuxer.parseChunks(e, t)), this._config.customDemuxer)
      this._setupCustomDemuxerRemuxer();
    else if (s == "hls")
      this._config.disableSortQueue = !0, this._setupRTCDemuxerRemuxer(), i = this._demuxer.parseChunks(e, t);
    else {
      let l = null;
      l = ja.probe(e), l.match && (this._setupFLVDemuxerRemuxer(l), i = this._demuxer.parseChunks(e, t)), !l.match && !l.needMoreData && (l = cf.probe(e), l.match && (this._setupTSDemuxerRemuxer(l), i = this._demuxer.parseChunks(e, t))), !l.match && !l.needMoreData && (l = null, S.e(this.TAG, "Non MPEG-TS/FLV, Unsupported media type!"), Promise.resolve().then(() => {
        this._internalAbort();
      }), this._emitter.emit(X.DEMUX_ERROR, Fe.FORMAT_UNSUPPORTED, "Non MPEG-TS/FLV, Unsupported media type!"));
    }
    return i;
  }
  _setupCustomDemuxerRemuxer() {
    const e = this._demuxer = new this._config.customDemuxer(this._config);
    if (!this._remuxer) {
      const i = this._config.customDemuxer ?? r0;
      this._remuxer = new i(this._config);
    }
    const t = this._mediaDataSource;
    typeof hasAudio == "boolean" && (e.overridedHasAudio = t.hasAudio), e.onError = this._onDemuxException.bind(this), e.onMediaInfo = this._onMediaInfo.bind(this), e.onMetaDataArrived = this._onMetaDataArrived.bind(this), this._remuxer.bindDataSource(this._demuxer), this._demuxer.bindDataSource(this._ioctl), this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this), this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  }
  _setupFLVDemuxerRemuxer(e) {
    this._demuxer = new ja(e, this._config), this._remuxer || (this._remuxer = new r0(this._config));
    let t = this._mediaDataSource;
    t.duration != null && !isNaN(t.duration) && (this._demuxer.overridedDuration = t.duration), typeof t.hasAudio == "boolean" && (this._demuxer.overridedHasAudio = t.hasAudio), typeof t.hasVideo == "boolean" && (this._demuxer.overridedHasVideo = t.hasVideo), this._demuxer.timestampBase = t.segments[this._currentSegmentIndex].timestampBase, this._demuxer.onError = this._onDemuxException.bind(this), this._demuxer.onMediaInfo = this._onMediaInfo.bind(this), this._demuxer.onMetaDataArrived = this._onMetaDataArrived.bind(this), this._demuxer.onScriptDataArrived = this._onScriptDataArrived.bind(this), this._demuxer.onCustomFlvMessage = this._onCustomMessage.bind(this), this._mediaBridge || (this._mediaBridge = new n0(this._config)), this._remuxer.bindDataSource(this._mediaBridge), this._demuxer.bindDataSource(this._ioctl), this._mediaBridge.onCompatibleVideo = this._onCompatibleVideo, this._mediaBridge.onCompatibleAudio = this._onCompatibleAudio, this._mediaBridge.onNoDataReceived = this._onNoDataReceived, this._mediaBridge.bindDataSource(this._demuxer), this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this), this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  }
  _setupTSDemuxerRemuxer(e) {
    let t = this._demuxer = new cf(e, this._config);
    this._remuxer || (this._remuxer = new r0(this._config));
    const i = this._mediaDataSource;
    typeof i.hasAudio == "boolean" && (this._demuxer.hasAudio = i.hasAudio), typeof i.hasVideo == "boolean" && (this._demuxer.hasVideo = i.hasVideo), t.onError = this._onDemuxException.bind(this), t.onMediaInfo = this._onMediaInfo.bind(this), t.onMetaDataArrived = this._onMetaDataArrived.bind(this), t.onCustomFlvMessage = this._onCustomMessage.bind(this), this._mediaBridge || (this._mediaBridge = new n0(this._config)), this._remuxer.bindDataSource(this._mediaBridge), this._demuxer.bindDataSource(this._ioctl), this._mediaBridge.onCompatibleVideo = this._onCompatibleVideo, this._mediaBridge.onCompatibleAudio = this._onCompatibleAudio, this._mediaBridge.onNoDataReceived = this._onNoDataReceived, this._mediaBridge.bindDataSource(this._demuxer), this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this), this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this);
  }
  _setupRTCDemuxerRemuxer() {
    this._demuxer = new RTCDemuxer(this._config);
    const e = this._mediaDataSource;
    typeof hasAudio == "boolean" && (this._demuxer.overridedHasAudio = e.hasAudio), this._demuxer.onError = this._onDemuxException.bind(this), this._demuxer.onMediaInfo = this._onMediaInfo.bind(this), this._demuxer.onCustomFlvMessage = this._onCustomMessage.bind(this), this._mediaBridge || (this._mediaBridge = new n0(this._config)), this._demuxer.bindDataSource(this._ioctl), this._mediaBridge.onCompatibleVideo = this._onCompatibleVideo, this._mediaBridge.onCompatibleAudio = this._onCompatibleAudio, this._mediaBridge.onNoDataReceived = this._onNoDataReceived, this._mediaBridge.bindDataSource(this._demuxer);
  }
  _onMediaInfo(e) {
    this._mediaInfo == null && (this._mediaInfo = Object.assign({}, e), this._mediaInfo.keyframesIndex = null, this._mediaInfo.segments = [], this._mediaInfo.segmentCount = this._mediaDataSource.segments.length, Object.setPrototypeOf(this._mediaInfo, Gs.prototype));
    let t = Object.assign({}, e);
    Object.setPrototypeOf(t, Gs.prototype), this._mediaInfo.segments[this._currentSegmentIndex] = t, this._reportSegmentMediaInfo(this._currentSegmentIndex), this._pendingSeekTime != null && Promise.resolve().then(() => {
      let i = this._pendingSeekTime;
      this._pendingSeekTime = null, this.seek(i);
    });
  }
  _onMetaDataArrived(e) {
    this._emitter.emit(X.METADATA_ARRIVED, e);
  }
  _onScriptDataArrived(e) {
    this._emitter.emit(X.SCRIPTDATA_ARRIVED, e);
  }
  _onCustomMessage(e) {
    var t;
    (t = this._emitter) == null || t.emit(X.CUSTOM_TRANSLATE_MESSAGE, e);
  }
  _onTimedID3Metadata(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.dts != null && (e.dts -= t), this._emitter.emit(X.TIMED_ID3_METADATA_ARRIVED, e));
  }
  _onPGSSubtitle(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.dts != null && (e.dts -= t), this._emitter.emit(X.PGS_SUBTITLE_ARRIVED, e));
  }
  _onSynchronousKLVMetadata(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.dts != null && (e.dts -= t), this._emitter.emit(X.SYNCHRONOUS_KLV_METADATA_ARRIVED, e));
  }
  _onAsynchronousKLVMetadata(e) {
    this._emitter.emit(X.ASYNCHRONOUS_KLV_METADATA_ARRIVED, e);
  }
  _onSMPTE2038Metadata(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.dts != null && (e.dts -= t), e.nearest_pts != null && (e.nearest_pts -= t), this._emitter.emit(X.SMPTE2038_METADATA_ARRIVED, e));
  }
  _onSCTE35Metadata(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.nearest_pts != null && (e.nearest_pts -= t), this._emitter.emit(X.SCTE35_METADATA_ARRIVED, e));
  }
  _onPESPrivateDataDescriptor(e) {
    this._emitter.emit(X.PES_PRIVATE_DATA_DESCRIPTOR, e);
  }
  _onPESPrivateData(e) {
    let t = this._remuxer.getTimestampBase();
    t != null && (e.pts != null && (e.pts -= t), e.nearest_pts != null && (e.nearest_pts -= t), e.dts != null && (e.dts -= t), this._emitter.emit(X.PES_PRIVATE_DATA_ARRIVED, e));
  }
  _onIOSeeked() {
    this._remuxer.insertDiscontinuity();
  }
  _onIOComplete(e) {
    let i = e + 1;
    i < this._mediaDataSource.segments.length ? (this._internalAbort(), this._remuxer && this._remuxer.flushStashedSamples(), this._loadSegment(i)) : (this._remuxer && this._remuxer.flushStashedSamples(), this._emitter.emit(X.LOADING_COMPLETE), this._disableStatisticsReporter());
  }
  _onIORedirect(e) {
    let t = this._ioctl.extraData;
    this._mediaDataSource.segments[t].redirectedURL = e;
  }
  _onIORecoveredEarlyEof() {
    this._emitter.emit(X.RECOVERED_EARLY_EOF);
  }
  _onIOException(e, t) {
    S.e(this.TAG, `IOException: type = ${e}, code = ${t.code}, msg = ${t.msg}`), this._emitter.emit(X.IO_ERROR, e, t), this._disableStatisticsReporter();
  }
  _onDemuxException(e, t) {
    S.e(this.TAG, `DemuxException: type = ${e}, info = ${t}`), this._emitter.emit(X.DEMUX_ERROR, e, t);
  }
  _onRemuxerInitSegmentArrival(e, t) {
    this._emitter.emit(X.INIT_SEGMENT, e, t);
  }
  _onRemuxerMediaSegmentArrival(e, t) {
    if (this._pendingSeekTime == null && (this._emitter.emit(X.MEDIA_SEGMENT, e, t), this._pendingResolveSeekPoint != null && e === "video")) {
      let i = t.info.syncPoints, s = this._pendingResolveSeekPoint;
      this._pendingResolveSeekPoint = null, ye.safari && i.length > 0 && i[0].originalDts === s && (s = i[0].pts), this._emitter.emit(X.RECOMMEND_SEEKPOINT, s);
    }
  }
  _enableStatisticsReporter() {
    this._statisticsReporter == null && (this._statisticsReporter = self.setInterval(
      this._reportStatisticsInfo.bind(this),
      this._config.statisticsInfoReportInterval
    ));
  }
  _disableStatisticsReporter() {
    this._statisticsReporter && (self.clearInterval(this._statisticsReporter), this._statisticsReporter = null);
  }
  _reportSegmentMediaInfo(e) {
    let t = this._mediaInfo.segments[e], i = Object.assign({}, t);
    i.duration = this._mediaInfo.duration, i.segmentCount = this._mediaInfo.segmentCount, delete i.segments, delete i.keyframesIndex, this._emitter.emit(X.MEDIA_INFO, i);
  }
  _reportStatisticsInfo() {
    let e = {};
    e.url = this._ioctl.currentURL, e.hasRedirect = this._ioctl.hasRedirect, e.hasRedirect && (e.redirectedURL = this._ioctl.currentRedirectedURL), e.speed = this._ioctl.currentSpeed, e.loaderType = this._ioctl.loaderType, e.currentSegmentIndex = this._currentSegmentIndex, e.totalSegmentCount = this._mediaDataSource.segments.length, this._emitter.emit(X.STATISTICS_INFO, e);
  }
}
let PA = class {
  constructor(e, t) {
    if (this.TAG = "Transmuxer", this._emitter = new ve(), t.enableWorker && typeof Worker < "u")
      try {
        this._worker = Rb(require.resolve("./transmuxing-worker")), this._workerDestroying = !1, this._worker.addEventListener("message", this._onWorkerMessage.bind(this)), this._worker.postMessage({ cmd: "init", param: [e, t] }), this.e = {
          onLoggingConfigChanged: this._onLoggingConfigChanged.bind(this)
        }, We.registerListener(this.e.onLoggingConfigChanged), this._worker.postMessage({ cmd: "logging_config", param: We.getConfig() });
      } catch {
        S.e(this.TAG, "Error while initialize transmuxing worker, fallback to inline transmuxing"), this._worker = null, this._controller = new pf(e, t);
      }
    else
      this._controller = new pf(e, t);
    if (this._controller) {
      let i = this._controller;
      i.on(X.IO_ERROR, this._onIOError.bind(this)), i.on(X.DEMUX_ERROR, this._onDemuxError.bind(this)), i.on(X.INIT_SEGMENT, this._onInitSegment.bind(this)), i.on(X.MEDIA_SEGMENT, this._onMediaSegment.bind(this)), i.on(X.LOADING_COMPLETE, this._onLoadingComplete.bind(this)), i.on(X.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this)), i.on(X.MEDIA_INFO, this._onMediaInfo.bind(this)), i.on(X.METADATA_ARRIVED, this._onMetaDataArrived.bind(this)), i.on(X.SCRIPTDATA_ARRIVED, this._onScriptDataArrived.bind(this)), i.on(X.TIMED_ID3_METADATA_ARRIVED, this._onTimedID3MetadataArrived.bind(this)), i.on(X.SYNCHRONOUS_KLV_METADATA_ARRIVED, this._onSynchronousKLVMetadataArrived.bind(this)), i.on(X.ASYNCHRONOUS_KLV_METADATA_ARRIVED, this._onAsynchronousKLVMetadataArrived.bind(this)), i.on(X.SMPTE2038_METADATA_ARRIVED, this._onSMPTE2038MetadataArrived.bind(this)), i.on(X.SCTE35_METADATA_ARRIVED, this._onSCTE35MetadataArrived.bind(this)), i.on(X.PES_PRIVATE_DATA_DESCRIPTOR, this._onPESPrivateDataDescriptor.bind(this)), i.on(X.PES_PRIVATE_DATA_ARRIVED, this._onPESPrivateDataArrived.bind(this)), i.on(X.STATISTICS_INFO, this._onStatisticsInfo.bind(this)), i.on(X.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this)), i.on(X.LOADED_COMPATIBLE_VIDEO, this._onCompatibleVideo.bind(this)), i.on(X.LOADED_COMPATIBLE_AUDIO, this._onCompatibleAudio.bind(this)), i.on(X.CUSTOM_TRANSLATE_MESSAGE, this._onCustomMessage.bind(this)), i.on(X.NO_DATA_RECEIVED, this._onNoDataReceived.bind(this));
    }
  }
  destroy() {
    this._worker ? this._workerDestroying || (this._workerDestroying = !0, this._worker.postMessage({ cmd: "destroy" }), We.removeListener(this.e.onLoggingConfigChanged), this.e = null) : (this._controller.destroy(), this._controller = null), this._emitter.removeAllListeners(), this._emitter = null;
  }
  on(e, t) {
    this._emitter.addListener(e, t);
  }
  off(e, t) {
    this._emitter.removeListener(e, t);
  }
  hasWorker() {
    return this._worker != null;
  }
  open() {
    this._worker ? this._worker.postMessage({ cmd: "start" }) : this._controller.start();
  }
  hungry(e) {
    this._worker ? this._worker.postMessage({ cmd: "hungry", param: e }) : this._controller.hungry(e);
  }
  setPlayTactics(e) {
    this._worker ? this._worker.postMessage({ cmd: "setPlayTactics", data: e }) : this._controller.setPlayTactics(e);
  }
  close() {
    this._worker ? this._worker.postMessage({ cmd: "stop" }) : this._controller.stop();
  }
  seek(e) {
    this._worker ? this._worker.postMessage({ cmd: "seek", param: e }) : this._controller.seek(e);
  }
  pause() {
    this._worker ? this._worker.postMessage({ cmd: "pause" }) : this._controller.pause();
  }
  resume() {
    this._worker ? this._worker.postMessage({ cmd: "resume" }) : this._controller.resume();
  }
  _onInitSegment(e, t) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.INIT_SEGMENT, e, t);
    });
  }
  _onMediaSegment(e, t) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.MEDIA_SEGMENT, e, t);
    });
  }
  _onLoadingComplete() {
    Promise.resolve().then(() => {
      this._emitter.emit(X.LOADING_COMPLETE);
    });
  }
  _onRecoveredEarlyEof() {
    Promise.resolve().then(() => {
      this._emitter.emit(X.RECOVERED_EARLY_EOF);
    });
  }
  _onMediaInfo(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.MEDIA_INFO, e);
    });
  }
  _onMetaDataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.METADATA_ARRIVED, e);
    });
  }
  _onScriptDataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.SCRIPTDATA_ARRIVED, e);
    });
  }
  _onTimedID3MetadataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.TIMED_ID3_METADATA_ARRIVED, e);
    });
  }
  _onPGSSubtitleArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.PGS_SUBTITLE_ARRIVED, e);
    });
  }
  _onSynchronousKLVMetadataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.SYNCHRONOUS_KLV_METADATA_ARRIVED, e);
    });
  }
  _onAsynchronousKLVMetadataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.ASYNCHRONOUS_KLV_METADATA_ARRIVED, e);
    });
  }
  _onSMPTE2038MetadataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.SMPTE2038_METADATA_ARRIVED, e);
    });
  }
  _onSCTE35MetadataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.SCTE35_METADATA_ARRIVED, e);
    });
  }
  _onPESPrivateDataDescriptor(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.PES_PRIVATE_DATA_DESCRIPTOR, e);
    });
  }
  _onPESPrivateDataArrived(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.PES_PRIVATE_DATA_ARRIVED, e);
    });
  }
  _onCustomMessage(e) {
    Promise.resolve().then(() => {
      this._emitter && this._emitter.emit(X.CUSTOM_TRANSLATE_MESSAGE, e);
    });
  }
  _onCompatibleVideo(e) {
    Promise.resolve().then(() => {
      this._emitter && this._emitter.emit(X.LOADED_COMPATIBLE_VIDEO, e);
    });
  }
  _onCompatibleAudio(e) {
    Promise.resolve().then(() => {
      this._emitter && this._emitter.emit(X.LOADED_COMPATIBLE_AUDIO, e);
    });
  }
  _onNoDataReceived() {
    Promise.resolve().then(() => {
      this._emitter && this._emitter.emit(X.NO_DATA_RECEIVED);
    });
  }
  _onStatisticsInfo(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.STATISTICS_INFO, e);
    });
  }
  _onIOError(e, t) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.IO_ERROR, e, t);
    });
  }
  _onDemuxError(e, t) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.DEMUX_ERROR, e, t);
    });
  }
  _onRecommendSeekpoint(e) {
    Promise.resolve().then(() => {
      this._emitter.emit(X.RECOMMEND_SEEKPOINT, e);
    });
  }
  _onLoggingConfigChanged(e) {
    this._worker && this._worker.postMessage({ cmd: "logging_config", param: e });
  }
  _onWorkerMessage(e) {
    let t = e.data, i = t.data;
    if (t.msg === "destroyed" || this._workerDestroying) {
      this._workerDestroying = !1, this._worker.terminate(), this._worker = null;
      return;
    }
    switch (t.msg) {
      case X.LOADED_COMPATIBLE_VIDEO:
        this._emitter.emit(t.msg, i);
        break;
      case X.LOADED_COMPATIBLE_AUDIO:
        this._emitter.emit(t.msg, i);
        break;
      case X.NO_DATA_RECEIVED:
        this._emitter.emit(t.msg);
        break;
      case X.CUSTOM_TRANSLATE_MESSAGE:
        this._emitter.emit(t.msg, i.message);
        break;
      case X.INIT_SEGMENT:
      case X.MEDIA_SEGMENT:
        this._emitter.emit(t.msg, i.type, i.data);
        break;
      case X.LOADING_COMPLETE:
      case X.RECOVERED_EARLY_EOF:
        this._emitter.emit(t.msg);
        break;
      case X.MEDIA_INFO:
        Object.setPrototypeOf(i, Gs.prototype), this._emitter.emit(t.msg, i);
        break;
      case X.METADATA_ARRIVED:
      case X.SCRIPTDATA_ARRIVED:
      case X.TIMED_ID3_METADATA_ARRIVED:
      case X.PGS_SUBTITLE_ARRIVED:
      case X.SYNCHRONOUS_KLV_METADATA_ARRIVED:
      case X.ASYNCHRONOUS_KLV_METADATA_ARRIVED:
      case X.SMPTE2038_METADATA_ARRIVED:
      case X.SCTE35_METADATA_ARRIVED:
      case X.PES_PRIVATE_DATA_DESCRIPTOR:
      case X.PES_PRIVATE_DATA_ARRIVED:
      case X.STATISTICS_INFO:
        this._emitter.emit(t.msg, i);
        break;
      case X.IO_ERROR:
      case X.DEMUX_ERROR:
        this._emitter.emit(t.msg, i.type, i.info);
        break;
      case X.RECOMMEND_SEEKPOINT:
        this._emitter.emit(t.msg, i);
        break;
      case "logcat_callback":
        S.emitter.emit("log", i.type, i.logcat);
        break;
    }
  }
};
class Ja {
  constructor(e, t, i) {
    y(this, "TAG", "SeekingHandler");
    y(this, "_config", null);
    y(this, "_media_element", null);
    y(this, "_always_seek_keyframe", !1);
    y(this, "_on_unbuffered_seek", null);
    y(this, "_request_set_current_time", !1);
    y(this, "_seek_request_record_clocktime", null);
    y(this, "_idr_sample_list", new DA());
    y(this, "e", null);
    this._config = e, this._media_element = t, this._on_unbuffered_seek = i, this.e = {
      onMediaSeeking: this._onMediaSeeking.bind(this)
    };
    let s = ye.chrome && (ye.version.major < 50 || ye.version.major === 50 && ye.version.build < 2661);
    this._always_seek_keyframe = !!(s || ye.msedge || ye.msie), this._always_seek_keyframe && (this._config.accurateSeek = !1), this._media_element.addEventListener("seeking", this.e.onMediaSeeking);
  }
  destroy() {
    this._idr_sample_list.clear(), this._idr_sample_list = null, this._media_element.removeEventListener("seeking", this.e.onMediaSeeking), this._media_element = null, this._on_unbuffered_seek = null;
  }
  seek(e) {
    const t = this._isPositionBuffered(e);
    let i = !1;
    if (e < 1 && this._media_element.buffered.length > 0) {
      const s = this._media_element.buffered.start(0);
      (s < 1 && e < s || ye.safari) && (i = !0, e = ye.safari ? 0.1 : s);
    }
    if (i)
      this.directSeek(e);
    else if (t)
      if (!this._always_seek_keyframe)
        this.directSeek(e);
      else {
        const s = this._getNearestKeyframe(Math.floor(e * 1e3));
        s != null && (e = s.dts / 1e3), this.directSeek(e);
      }
    else
      this._idr_sample_list.clear(), this._on_unbuffered_seek(Math.floor(e * 1e3)), this._config.accurateSeek && this.directSeek(e);
  }
  directSeek(e) {
    this._request_set_current_time = !0, this._media_element.currentTime = e;
  }
  appendSyncPoints(e) {
    this._idr_sample_list.appendArray(e);
  }
  // Handle seeking request from browser's progress bar or HTMLMediaElement.currentTime setter
  _onMediaSeeking(e) {
    if (this._request_set_current_time) {
      this._request_set_current_time = !1;
      return;
    }
    let t = this._media_element.currentTime;
    const i = this._media_element.buffered;
    if (t < 1 && i.length > 0) {
      let s = i.start(0);
      if (s < 1 && t < s || ye.safari) {
        let n = ye.safari ? 0.1 : s;
        this.directSeek(n);
        return;
      }
    }
    if (this._isPositionBuffered(t)) {
      if (this._always_seek_keyframe) {
        const s = this._getNearestKeyframe(Math.floor(t * 1e3));
        s != null && (t = s.dts / 1e3, this.directSeek(t));
      }
      return;
    }
    this._seek_request_record_clocktime = Ja._getClockTime(), window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this), 50);
  }
  _pollAndApplyUnbufferedSeek() {
    if (this._seek_request_record_clocktime == null)
      return;
    if (this._seek_request_record_clocktime <= Ja._getClockTime() - 100) {
      const t = this._media_element.currentTime;
      this._seek_request_record_clocktime = null, this._isPositionBuffered(t) || (this._idr_sample_list.clear(), this._on_unbuffered_seek(Math.floor(t * 1e3)), this._config.accurateSeek && this.directSeek(t));
    } else
      window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this), 50);
  }
  _isPositionBuffered(e) {
    const t = this._media_element.buffered;
    for (let i = 0; i < t.length; i++) {
      const s = t.start(i), n = t.end(i);
      if (e >= s && e < n)
        return !0;
    }
    return !1;
  }
  _getNearestKeyframe(e) {
    return this._idr_sample_list.getLastSyncPointBeforeDts(e);
  }
  static _getClockTime() {
    return self.performance && self.performance.now ? self.performance.now() : Date.now();
  }
}
class kA {
  constructor(e, t, i, s) {
    y(this, "TAG", "LoadingController");
    y(this, "_config", null);
    y(this, "_media_element", null);
    y(this, "_on_pause_transmuxer", null);
    y(this, "_on_resume_transmuxer", null);
    y(this, "_paused", !1);
    y(this, "e", null);
    this._config = e, this._media_element = t, this._on_pause_transmuxer = i, this._on_resume_transmuxer = s, this.e = {
      onMediaTimeUpdate: this._onMediaTimeUpdate.bind(this)
    };
  }
  destroy() {
    this._media_element.removeEventListener("timeupdate", this.e.onMediaTimeUpdate), this.e = null, this._media_element = null, this._config = null, this._on_pause_transmuxer = null, this._on_resume_transmuxer = null;
  }
  // buffered_position: in seconds
  notifyBufferedPositionChanged(e) {
    this._config.isLive || !this._config.lazyLoad || (e == null ? this._suspendTransmuxerIfNeeded() : this._suspendTransmuxerIfBufferedPositionExceeded(e));
  }
  _onMediaTimeUpdate(e) {
    this._paused && this._resumeTransmuxerIfNeeded();
  }
  _suspendTransmuxerIfNeeded() {
    const e = this._media_element.buffered, t = this._media_element.currentTime;
    let i = 0;
    for (let s = 0; s < e.length; s++) {
      const n = e.start(s), a = e.end(s);
      if (n <= t && t < a) {
        i = a;
        break;
      }
    }
    i > 0 && this._suspendTransmuxerIfBufferedPositionExceeded(i);
  }
  _suspendTransmuxerIfBufferedPositionExceeded(e) {
    const t = this._media_element.currentTime;
    e >= t + this._config.lazyLoadMaxDuration && !this._paused && (S.v(this.TAG, "Maximum buffering duration exceeded, suspend transmuxing task"), this.suspendTransmuxer(), this._media_element.addEventListener("timeupdate", this.e.onMediaTimeUpdate));
  }
  suspendTransmuxer() {
    this._paused = !0, this._on_pause_transmuxer();
  }
  _resumeTransmuxerIfNeeded() {
    const e = this._media_element.buffered, t = this._media_element.currentTime, i = this._config.lazyLoadRecoverDuration;
    let s = !1;
    for (let n = 0; n < e.length; n++) {
      const a = e.start(n), o = e.end(n);
      if (t >= a && t < o) {
        t >= o - i && (s = !0);
        break;
      }
    }
    s && (S.v(this.TAG, "Continue loading from paused position"), this.resumeTransmuxer(), this._media_element.removeEventListener("timeupdate", this.e.onMediaTimeUpdate));
  }
  resumeTransmuxer() {
    this._paused = !1, this._on_resume_transmuxer();
  }
}
class wA {
  constructor(e, t) {
    y(this, "TAG", "StartupStallJumper");
    y(this, "_media_element", null);
    y(this, "_on_direct_seek", null);
    y(this, "_canplay_received", !1);
    y(this, "e", null);
    this._media_element = e, this._on_direct_seek = t, this.e = {
      onMediaCanPlay: this._onMediaCanPlay.bind(this),
      onMediaStalled: this._onMediaStalled.bind(this),
      onMediaProgress: this._onMediaProgress.bind(this)
    }, this._media_element.addEventListener("canplay", this.e.onMediaCanPlay), this._media_element.addEventListener("stalled", this.e.onMediaStalled), this._media_element.addEventListener("progress", this.e.onMediaProgress);
  }
  destroy() {
    this._media_element.removeEventListener("canplay", this.e.onMediaCanPlay), this._media_element.removeEventListener("stalled", this.e.onMediaStalled), this._media_element.removeEventListener("progress", this.e.onMediaProgress), this._media_element = null, this._on_direct_seek = null;
  }
  _onMediaCanPlay(e) {
    this._canplay_received = !0, this._media_element.removeEventListener("canplay", this.e.onMediaCanPlay);
  }
  _onMediaStalled(e) {
    this._detectAndFixStuckPlayback(!0);
  }
  _onMediaProgress(e) {
    this._detectAndFixStuckPlayback();
  }
  _detectAndFixStuckPlayback(e) {
    const t = this._media_element, i = t.buffered;
    e || !this._canplay_received || t.readyState < 2 ? i.length > 0 && t.currentTime < i.start(0) && (S.w(this.TAG, `Playback seems stuck at ${t.currentTime}, seek to ${i.start(0)}`), this._on_direct_seek(i.start(0)), this._media_element.removeEventListener("progress", this.e.onMediaProgress)) : this._media_element.removeEventListener("progress", this.e.onMediaProgress);
  }
}
class MA {
  constructor(e, t, i) {
    y(this, "_config", null);
    y(this, "_media_element", null);
    y(this, "_on_direct_seek", null);
    this._config = e, this._media_element = t, this._on_direct_seek = i;
  }
  destroy() {
    this._on_direct_seek = null, this._media_element = null, this._config = null;
  }
  notifyBufferedRangeUpdate() {
    this._chaseLiveLatency();
  }
  _chaseLiveLatency() {
    const e = this._media_element.buffered, t = this._media_element.currentTime, i = this._media_element.paused;
    if (!this._config.isLive || !this._config.liveBufferLatencyChasing || e.length == 0 || !this._config.liveBufferLatencyChasingOnPaused && i)
      return;
    const s = e.end(e.length - 1);
    if (s > this._config.liveBufferLatencyMaxLatency && s - t > this._config.liveBufferLatencyMaxLatency) {
      let n = s - this._config.liveBufferLatencyMinRemain;
      this._on_direct_seek(n);
    }
  }
}
class BA {
  constructor(e, t) {
    y(this, "_config", null);
    y(this, "_media_element", null);
    y(this, "e", null);
    this._config = e, this._media_element = t, this.e = {
      onMediaTimeUpdate: this._onMediaTimeUpdate.bind(this)
    }, this._media_element.addEventListener("timeupdate", this.e.onMediaTimeUpdate);
  }
  destroy() {
    this._media_element.removeEventListener("timeupdate", this.e.onMediaTimeUpdate), this._media_element = null, this._config = null;
  }
  _onMediaTimeUpdate(e) {
    if (!this._config.isLive || !this._config.liveSync)
      return;
    const t = this._getCurrentLatency();
    if (t > this._config.liveSyncMaxLatency) {
      const i = Math.min(2, Math.max(1, this._config.liveSyncPlaybackRate));
      this._media_element.playbackRate = i;
    } else t > this._config.liveSyncTargetLatency || this._media_element.playbackRate !== 1 && this._media_element.playbackRate !== 0 && (this._media_element.playbackRate = 1);
  }
  _getCurrentLatency() {
    if (!this._media_element)
      return 0;
    const e = this._media_element.buffered, t = this._media_element.currentTime;
    return e.length == 0 ? 0 : e.end(e.length - 1) - t;
  }
}
const FA = {
  [jt.Video]: 4e3,
  [jt.Audio]: 0
};
var Mt = /* @__PURE__ */ ((r) => (r.WCSVideoDecoder = "WCSVideoDecoder", r.WasmVideoDecoder = "WasmVideoDecoder", r.WCSAudioDecoder = "WCSAudioDecoder", r.G711Decoder = "G711Decoder", r.AACDecoder = "AACDecoder", r))(Mt || {});
class bg extends ve {
  /**
   *
   * @param {*} decodeType 解码器类型
   * @param {*} enctype 编码类型
   * @param {*} type video/audio
   * @param {*} traceId traceId
   */
  constructor(t, i, s, n) {
    super();
    y(this, "TAG");
    y(this, "decoderType");
    y(this, "encodeType");
    y(this, "mediaType");
    y(this, "startDecodeTimes", []);
    y(this, "dequeueSize", 0);
    y(this, "errorCheckTime", 0);
    y(this, "decodeErrorOccur", !1);
    this.decoderType = t, this.TAG = S.traceTag(t, n), this.encodeType = i, this.mediaType = s, this.errorCheckTime = FA[s];
  }
  resetEncodeType(t) {
    this.dequeueSize = 0, this.encodeType = t, this.startDecodeTimes = [];
  }
  decodeStart(t) {
    const { dts: i, duration: s, isKeyframe: n } = t;
    this.dequeueSize++;
    const a = this.errorCheckTime, o = Qi();
    if (a && this.startDecodeTimes.length && o - this.startDecodeTimes[0].start > a) {
      this.decodeError(`${this.mediaType} timeout! Not receiving decoded frames for too long [${a}ms]`);
      return;
    }
    this.startDecodeTimes.push({ start: o, dts: i, duration: s, isKeyframe: n });
  }
  decodeEnd(t, ...i) {
    const { start: s = 0, dts: n, duration: a, isKeyframe: o } = this.startDecodeTimes.shift() || {}, c = Qi() - s;
    this.emit("data", { data: t, time: c, timestamp: n, duration: a, isKeyframe: o }, ...i), this.dequeueSize--;
  }
  decodeError(t) {
    this.dequeueSize--, !this.decodeErrorOccur && (this.decodeErrorOccur = !0, S.e(this.TAG, `${this.mediaType} decode error, `, (t == null ? void 0 : t.message) || (t == null ? void 0 : t.stack) || (t == null ? void 0 : t.toString())), this.emit("error", t));
  }
  destroy() {
    this.dequeueSize = 0, this.removeAllListeners(), this.startDecodeTimes = [];
  }
}
class OA extends bg {
  /**
   *Creates an instance of BaseVideoDecoder.
   * @param {*} decoderType 解码器类型
   * @param {*} type 0 H264 1 H265
   * @param {*} traceId 跟踪ID
   * @memberof BaseVideoDecoder
   */
  constructor(e, t, i) {
    super(e, t, jt.Video, i);
  }
}
const NA = ye, Sc = navigator.hardwareConcurrency || 1;
let Tc = Sc * (Sc < 2 ? 1 : 1.5);
NA.electron && (Tc = Math.min(Sc, Tc));
const mf = "WorkerPool";
var Us = /* @__PURE__ */ ((r) => (r.LoadStream = "LoadStreamWorker", r.DecodeWCSVideo = "WCSVideoWorker", r.DecodeWasmVideo = "WasmVideoDecoder", r.DecodeG711Audio = "G711AudioWorker", r.DecodeAACAudio = "AACAudioWorker", r.DecodeWCSAudio = "WCSAudioWorker", r))(Us || {});
const gf = Mm + "_web_sdk_worker_pool", Yn = self[gf] = self[gf] || {}, bc = {
  returnWorkerToPool: function(r, e, t) {
    const { unusedWorkers: i, runningWorkers: s } = Yn[r] || {};
    i.push(e), s.splice(s.indexOf(e), 1), S.i(S.traceTag(mf, t), `returnWorkerToPool ${r} runningWorkers.length=${s.length} unusedWorkers.length=${i.length}`);
  },
  getWorkerCnt() {
    let r = 0;
    return Object.values(Yn).forEach((e) => {
      const { unusedWorkers: t = [], runningWorkers: i = [] } = e || {};
      r += t.length + i.length;
    }), r;
  },
  getNewWorker: function(r, e, t) {
    let { unusedWorkers: i, runningWorkers: s } = Yn[r] || {};
    if (i || (i = [], s = [], Yn[r] = { unusedWorkers: i, runningWorkers: s }), i.length == 0) {
      const a = bc.getWorkerCnt();
      if (a >= Tc) return a;
      i.push(e);
    }
    const n = i.pop();
    return n && s.push(n), S.i(S.traceTag(mf, t), `${r} getNewWorker ${r} runningWorkers.length=${s.length} unusedWorkers.length=${i.length}`), e;
  },
  busySpinWait: function(r) {
    let e = performance.now() + r;
    for (; performance.now() < e; )
      ;
  }
}, _f = ye, GA = 3;
class _s {
  constructor(e, t, i, s = !1) {
    y(this, "TAG");
    y(this, "worker");
    y(this, "disabledPool");
    y(this, "workerId", _o());
    y(this, "traceId");
    y(this, "workerType");
    y(this, "workerDestroying", !1);
    y(this, "retryPingCnt", 0);
    y(this, "noPongTimer", -1);
    y(this, "pingpongTimer", -1);
    y(this, "onWorkerMessage");
    y(this, "handleWorkerMessage", (e) => {
      var n, a, o;
      let { msg: t, data: i, workerId: s } = e.data;
      if (t === "logcat_callback") {
        const c = [i.logcat];
        i.style && c.push(i.style), (a = (n = S.getLogger())[i.type]) == null || a.call(n, ...c);
        return;
      }
      if (t === "destroyed" || this.workerDestroying) {
        if (this.workerId !== s) return;
        S.d(this.TAG, "destroyed worker. msg=" + t), this.destroyWorker();
        return;
      }
      switch (this.retryPingCnt = 0, this.ping(), t) {
        case "worker_pong":
          S.d(this.TAG, "receive worker pong");
          break;
        default:
          (o = this.onWorkerMessage) == null || o.call(this, e);
          break;
      }
    });
    y(this, "onLoggingConfigChanged", (e) => {
      this.postMessage({ cmd: "logging_config", data: { ...e, enableCallback: _f.electron } });
    });
    y(this, "noPong", () => {
      if (S.e(this.TAG, `main thread don't receive pong message.retry cnt=${this.retryPingCnt}`), this.retryPingCnt >= GA) {
        this.destroy(), this.destroyWorker();
        return;
      }
      this.retryPingCnt++, this.ping(Zt * this.retryPingCnt);
    });
    if (this.TAG = S.traceTag("WorkerController", i, t), !_s.isSupport(t))
      throw new Error(`unsupport worker type=${t}`);
    this.disabledPool = s;
    const n = s ? e : bc.getNewWorker(t, e, i);
    if (Number.isInteger(n))
      throw new Error(`too many worker,counter=${n}, type=${t}`);
    this.worker = n, this.traceId = i, this.workerType = t, this.workerDestroying = !1, this.retryPingCnt = 0, this.initClass();
  }
  static isSupport(e) {
    return ![Us.DecodeWCSVideo, Us.DecodeWCSAudio].includes(e);
  }
  init(e, t) {
    this.postMessage({ cmd: "init", data: e, traceId: t, workerId: this.workerId, workType: this.workerType });
  }
  postMessage(e, t = []) {
    var i;
    (i = this.worker) == null || i.postMessage(e, t);
  }
  destroy() {
    !this.worker || this.workerDestroying || (clearTimeout(this.noPongTimer), clearTimeout(this.pingpongTimer), this.workerDestroying = !0, this.postMessage({ cmd: "destroy" }));
  }
  destroyWorker() {
    if (!this.worker) return;
    clearTimeout(this.noPongTimer), clearTimeout(this.pingpongTimer), this.workerDestroying = !1;
    const e = this.worker;
    We.removeListener(this.onLoggingConfigChanged), e.removeEventListener("message", this.handleWorkerMessage), this.disabledPool ? e.terminate() : bc.returnWorkerToPool(this.workerType, e, this.traceId), this.worker = void 0;
  }
  initClass() {
    var e;
    (e = this.worker) == null || e.addEventListener("message", this.handleWorkerMessage), We.registerListener(this.onLoggingConfigChanged), this.postMessage({ cmd: "logging_config", data: { ...We.getConfig(), enableCallback: _f.electron } }), this.ping();
  }
  ping(e) {
    clearTimeout(this.noPongTimer), clearTimeout(this.pingpongTimer), this.pingpongTimer = setTimeout(() => {
      S.d(this.TAG, "main send ping"), this.postMessage({ cmd: "main_ping" }), this.noPongTimer = setTimeout(this.noPong, Zt * 3);
    }, e ?? 10 * Zt);
  }
}
const UA = self.VideoDecoder, VA = self.EncodedVideoChunk;
class WA extends ve {
  /**
   *Creates an instance of WCSVideoDecoderImpl.
   * @param {*} config
   * @param {*} traceId
   * @memberof WCSVideoDecoderImpl
   */
  constructor(t, i) {
    super();
    y(this, "TAG");
    y(this, "decodeCnt", 0);
    y(this, "renderList", []);
    y(this, "decodeQueue", []);
    y(this, "decoder");
    y(this, "handleDequeue", () => {
      if (this.decodeCnt++, this.decodeQueue.length) {
        const t = this.decodeQueue.shift();
        t && this.decodeFrame(t);
      }
    });
    y(this, "handleFrame", (t) => {
      this.renderList.shift() || t.close(), this.emit("data", t);
    });
    y(this, "handleError", (t) => {
      S.e(this.TAG, "handleError", (t == null ? void 0 : t.message) || (t == null ? void 0 : t.stack) || (t == null ? void 0 : t.toString())), this.emit("error", t);
    });
    this.TAG = S.traceTag("WCSVideoDecoderImpl", i);
    const s = this.decoder = new UA({
      output: this.handleFrame,
      error: this.handleError
    });
    s.addEventListener && s.addEventListener("dequeue", this.handleDequeue), s.configure(t);
  }
  decode(t) {
    var l;
    const { data: i, dts: s, isKeyframe: n, duration: a, isRender: o } = t;
    this.renderList.push(o);
    const c = new VA({
      timestamp: s * 1e3,
      type: n ? "key" : "delta",
      data: i,
      duration: a * 1e3
    });
    (l = this.decoder) != null && l.addEventListener && (this.decoder.decodeQueueSize > 0 || this.decodeQueue.length) ? this.decodeQueue.push(c) : this.decodeFrame(c);
  }
  reset(t) {
    var i;
    ((i = this.decoder) == null ? void 0 : i.state) === "configured" && (this.renderList = [], this.decodeQueue = [], this.decodeCnt = 0, this.decoder.reset(), this.decoder.configure(t));
  }
  decodeFrame(t) {
    var i, s, n, a;
    if (((i = this.decoder) == null ? void 0 : i.state) !== "configured") {
      S.w(this.TAG, "decodeFrame decoder state=" + ((s = this.decoder) == null ? void 0 : s.state)), this.emit("error", { type: "stateerror", message: `${this.TAG} state=${(n = this.decoder) == null ? void 0 : n.state}` });
      return;
    }
    (a = this.decoder) == null || a.decode(t);
  }
  destroy() {
    this.renderList = [], this.decodeQueue = [], this.removeAllListeners();
    let t = this.decoder;
    t && (t.state !== "closed" && t.close(), t = this.decoder = void 0);
  }
}
const Ag = " ", HA = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)), yf = typeof self < "u" && self.Blob && new Blob([HA(Ag)], { type: "text/javascript;charset=utf-8" });
function ZA(r) {
  let e;
  try {
    if (e = yf && (self.URL || self.webkitURL).createObjectURL(yf), !e) throw "";
    const t = new Worker(e, {
      name: r == null ? void 0 : r.name
    });
    return t.addEventListener("error", () => {
      (self.URL || self.webkitURL).revokeObjectURL(e);
    }), t;
  } catch {
    return new Worker(
      "data:text/javascript;base64," + Ag,
      {
        name: r == null ? void 0 : r.name
      }
    );
  } finally {
    e && (self.URL || self.webkitURL).revokeObjectURL(e);
  }
}
const xf = self.VideoDecoder, gr = class gr extends OA {
  /**
   *Creates an instance of WCSVideoDecoder.
   * @param {*} type 0 H264 1 H265
   * @param {*} {meta :{codec,codecWidth,codecHeight}}
   * @memberof WCSVideoDecoder
   */
  constructor(t, i) {
    let { enableVideoWorker: s, manaulGCInterval: n, traceId: a } = i;
    super(Mt.WCSVideoDecoder, t.codecType, a);
    y(this, "lastDts", 0);
    y(this, "cnt", 0);
    // private dropCnt = 0;
    y(this, "needKeyFrame", !0);
    y(this, "worker");
    y(this, "decoder");
    y(this, "_onWorkerMessage", (t) => {
      let i = t.data, s = i.data;
      switch (i.msg) {
        case "data":
          this.decodeEnd(s);
          break;
        case "error":
          this.decodeError(t);
          break;
      }
    });
    const o = gr.getConfig(t), c = Us.DecodeWCSVideo;
    if (s && typeof Worker < "u" && _s.isSupport(c))
      try {
        this.worker = new _s(new ZA(), c, a), this.worker.onWorkerMessage = this._onWorkerMessage, this.worker.init({ config: o, manaulGCInterval: n }, a);
      } catch (l) {
        S.e(this.TAG, "Error while initialize WCSVideoDecoder worker, fallback to inline WCSVideoDecoder", (l == null ? void 0 : l.message) || (l == null ? void 0 : l.stack) || (l == null ? void 0 : l.toString())), this.worker = void 0;
      }
    if (!this.worker) {
      const l = this.decoder = new WA(o, a);
      l.on("data", (d) => super.decodeEnd(d)), l.on("error", this.decodeError);
    }
  }
  static getConfig(t) {
    const { codec: i, codecWidth: s, codecHeight: n } = t, a = {
      codec: i,
      codedWidth: s,
      codedHeight: n
    };
    return i.toLowerCase().includes("avc") && n > 1080 && (a.hardwareAcceleration = "prefer-software"), a;
  }
  static async isSupport(t) {
    if (!xf) return !1;
    const i = gr.getConfig(t);
    try {
      const { supported: s = !1 } = await xf.isConfigSupported(i);
      return s;
    } catch {
      return !1;
    }
  }
  reset(t) {
    var n;
    const { codecType: i } = t;
    this.resetEncodeType(i);
    const s = gr.getConfig(t);
    this.worker ? this.worker.postMessage({ cmd: "reset", data: s }) : (n = this.decoder) == null || n.reset(s), this.needKeyFrame = !0;
  }
  decode(t, i) {
    var c;
    const { data: s, dts: n, isKeyframe: a, duration: o } = t;
    if (!a && n < this.lastDts && S.w(this.TAG, ` dts[${n}] less than last dts[${this.lastDts}]`), !this.needKeyFrame && !a && this.lastDts && n - this.lastDts > 200 && (S.w(this.TAG, `maybe lost frame, dts:${n} gap:${n - this.lastDts} cnt=${this.cnt}`), this.cnt < 4 && (this.needKeyFrame = !0)), this.needKeyFrame) {
      if (!a)
        return S.w(this.TAG, `need keyframe, drop frame, dts:${n} gap:${this.lastDts ? n - this.lastDts : 0}`), this.lastDts = n, 0;
      this.needKeyFrame = !1;
    }
    a && (this.cnt = 0), this.cnt++;
    try {
      const l = { data: s, dts: n, isKeyframe: a, duration: o, isRender: i };
      this.worker ? this.worker.postMessage({ cmd: "decode", data: l }, [s.buffer]) : (c = this.decoder) == null || c.decode(l), this.lastDts = n, this.decodeStart({ dts: n, duration: o, isKeyframe: a });
    } catch (l) {
      S.e(this.TAG, "decode error", (l == null ? void 0 : l.message) || (l == null ? void 0 : l.stack) || (l == null ? void 0 : l.toString()));
    }
    return 0;
  }
  destroy() {
    var t;
    super.destroy(), this.worker ? this.worker.destroy() : ((t = this.decoder) == null || t.destroy(), this.decoder = void 0);
  }
};
y(gr, "CLASSNAME", Mt.WCSVideoDecoder);
let _n = gr;
class $A {
  constructor(e, t, i, s) {
    y(this, "naluType");
    y(this, "data");
    y(this, "dts");
    y(this, "duration", 0);
    y(this, "extras");
    y(this, "isKeyframe", !1);
    this.data = e, this.naluType = t, this.dts = i, this.extras = s || {};
  }
  free() {
    this.data = void 0;
  }
  checkVideoKeyFrame() {
    const { videoMeta: e } = this.extras;
    let t = this.naluType, i = !1;
    if (e) {
      const s = e.codecType;
      s === de.H265 ? i = t >= 16 && t <= 21 : s === de.H264 && (i = t === 5);
    }
    this.isKeyframe = i;
  }
}
class vf {
  /**
   *
   * @param {*} type MediaTypeEnum
   * @param {*} trackOptions WCSMediaTrackOptions
   */
  constructor(e, t = {}, i) {
    y(this, "TAG");
    y(this, "type");
    y(this, "startCache");
    y(this, "startPlay");
    y(this, "newestKeyframeIndex", -1);
    y(this, "lastKeyFrameIndex", -1);
    y(this, "index", -1);
    y(this, "state", 0);
    y(this, "lastClearIndex", 0);
    y(this, "isCached", !1);
    y(this, "lastFrame");
    y(this, "queue", []);
    y(this, "gopDuration", 0);
    let { startCache: s = 50, startPlay: n } = t;
    (!n || n - s < 200) && (n = s + 200), this.TAG = S.traceTag("WCSMediaTrack", i, e), this.startCache = s, this.startPlay = n, this.type = e, this.clear(!0);
  }
  clear(e = !1) {
    e || S.d(this.TAG, `${this.type} track clear called!!!`), this.queue = [], this.lastFrame = void 0, this.index = -1, this.state = 0, this.lastKeyFrameIndex = -1, this.newestKeyframeIndex = -1, this.gopDuration = 0, this.lastClearIndex = 0, this.isCached = !1;
  }
  get newestKeyframe() {
    return this.queue[this.newestKeyframeIndex];
  }
  get lastKeyframe() {
    return this.queue[this.lastKeyFrameIndex];
  }
  get buffered() {
    return {
      start: () => this.length ? this.getFrame(0).dts / Zt : 0,
      end: () => {
        const { dts: e = 0, duration: t = 0 } = this.lastFrame || {};
        return (e + t) / Zt;
      }
    };
  }
  get length() {
    return this.queue.length;
  }
  get currentFrame() {
    return this.getFrame(this.index);
  }
  get currenTime() {
    var e;
    return ((e = this.currentFrame) == null ? void 0 : e.dts) || 0;
  }
  get duration() {
    return this.buffered.end() * Zt;
  }
  get remain() {
    return this.duration - this.currenTime;
  }
  getFrames(e, t) {
    const i = this.queue.length, s = [];
    for (let n = 0; n < i; n++) {
      const a = this.getFrame(n);
      a.dts >= e && a.dts <= t && s.push(a);
    }
    return s;
  }
  getFrame(e) {
    return this.queue[e];
  }
  add(e) {
    const t = this.lastFrame;
    t && (t.duration = e.dts - t.dts, this.addToQueue(t)), this.lastFrame = e;
  }
  addToQueue(e) {
    this.queue.push(e);
    const { isKeyframe: t, extras: i = {} } = e;
    if (t) {
      const n = this.queue[this.newestKeyframeIndex];
      this.newestKeyframeIndex = this.queue.length - 1, n ? this.gopDuration = e.dts - n.dts : this.lastKeyFrameIndex = this.newestKeyframeIndex;
    }
    const { isStaticFrame: s } = i;
    s && this.lastKeyframe && (e.isKeyframe = !0, e.data = this.lastKeyframe.data);
  }
  canPlay() {
    const e = this.type === jt.Video;
    let t = (this.isCached || this.remain >= this.startPlay) && this.state !== 1;
    if (t && !this.isCached)
      S.d(this.TAG, `call canPlay. playing remain=${this.remain}`), this.isCached = !0;
    else if (!this.isCached && e && this.length && this.index < 0) return !0;
    return this.isCached && this.remain <= this.startCache && (S.d(this.TAG, `call canPlay. buffering remain=${this.remain}. startplay=${this.startPlay}`), this.isCached = !1), t;
  }
  playStart() {
    this.state = 1;
  }
  playStop() {
    this.state = 0;
  }
  nextFrame(e = !1) {
    const t = this.index + 1, i = this.getFrame(t);
    return !e && i && (this.index = t, i.isKeyframe && (this.lastKeyFrameIndex = t)), i;
  }
  seek(e) {
    const t = this.length;
    let i = this.lastClearIndex;
    for (; i < t; i++) {
      const s = this.getFrame(i);
      if (s.isKeyframe && (this.lastKeyFrameIndex = i), e < s.dts) break;
    }
    return this.index = i - 1, this.queue.slice(this.lastKeyFrameIndex, this.index + 1);
  }
  /**
   * 清除某时间点之前的历史数据
   * @param {*} time 时间
   * @param {*} freeAll  true 清除队列之前的所有帧对象，  false 只清帧对象的数据字段
   */
  clearBeforeTime(e, t = !1) {
    let i = this.lastClearIndex;
    const s = this.length;
    for (; i < s; ++i) {
      let n = this.getFrame(i);
      if (n.dts >= e) {
        this.lastClearIndex = i;
        break;
      }
      t || n.free();
    }
    if (t) {
      const n = this.lastClearIndex;
      this.queue = this.queue.slice(n), this.index -= n, this.lastKeyFrameIndex -= n, this.newestKeyframeIndex -= n, this.lastClearIndex = 0;
    }
  }
}
class KA {
  constructor() {
    // private TAG = 'NumberQueue';
    y(this, "list", []);
  }
  push(e, t) {
    this.list.push({ key: +e, value: +t });
  }
  fetch(e) {
    const t = this.list, i = t.length;
    if (i)
      for (let s = i - 1; s >= 0; s--) {
        const { key: n, value: a } = t[s];
        if (n <= e)
          return t.splice(0, s + 1), a;
      }
  }
  clear() {
    this.list = [];
  }
}
function XA(r) {
  const e = r.length;
  if (e < 2) return r[0];
  let t = r.reduce((s, n) => s + n.length, 0);
  const i = new r[0].constructor(t);
  return r.forEach((s, n) => {
    let a = n, o = s.length;
    for (let c = 0; c < o; c++)
      i[a] = s[c], a += e;
  }), i;
}
function Cg(r, e, t) {
  let { data: i } = r;
  const { channelCount: s, audioSampleRate: n } = e, a = zA(i);
  t || (t = new (window.AudioContext || window.webkitAudioContext)());
  const o = a.length, c = t.createBuffer(s, o, n), l = a.length;
  for (let d = 0; d < s; ++d) {
    let h = c.getChannelData(d), u = 0;
    for (let f = d; f < l; f += s, ++u)
      h[u] = a[f];
  }
  return c;
}
function YA(r) {
  const { format: e, numberOfChannels: t } = r, i = e != null && e.startsWith("s16") ? Int16Array : e != null && e.startsWith("s32") ? Int32Array : e != null && e.startsWith("f32") ? Float32Array : Uint8Array, s = [];
  for (let n = 0; n < t; n++)
    try {
      const a = r.allocationSize({ planeIndex: n }), o = new ArrayBuffer(a);
      r.copyTo(o, { planeIndex: n });
      const c = new i(o);
      if (t < 2) return c;
      s.push(c);
    } catch {
    }
  return XA(s);
}
function zA(r) {
  if (r instanceof Float32Array) return r;
  let e = r.length, t = new Float32Array(e);
  for (let i = 0; i != e; ++i)
    t[i] = r[i] / 32768;
  return t;
}
class jA {
  constructor(e) {
    //@ts-ignore
    y(this, "audioCtxt", new (window.AudioContext || window.webkitAudioContext)());
    y(this, "distOptions");
    y(this, "srcOptions");
    const { dist: t, src: i } = e;
    this.distOptions = t, this.srcOptions = i;
  }
  /**
   * 重新采样
   * @param {*} data Uint8Array
   * @returns
   */
  resample(e) {
    if (!this.audioCtxt) return;
    const { audioSampleRate: t, channelCount: i } = this.srcOptions, s = {
      data: e
    }, n = {
      codec: Ca(ae.PCM),
      audioSampleRate: t,
      channelCount: i,
      codecType: ae.PCM
    }, a = Cg(s, n, this.audioCtxt);
    return this.resampleAudioBuffer(a);
  }
  /**
   * 重新采样
   * @param {*} audioBuffer AudioBuffer
   * @returns
   */
  resampleAudioBuffer(e) {
    const { audioSampleRate: t, channelCount: i } = this.distOptions, s = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(i, e.duration * t, t);
    return new Promise((n) => {
      const a = s.createBufferSource();
      s.oncomplete = (o) => {
        n(o.renderedBuffer);
      }, a.buffer = e, a.connect(s.destination), a.start(0), s.startRendering();
    });
  }
  destroy() {
    this.audioCtxt = void 0;
  }
}
const a0 = ye, Ef = a0.mobile && (a0.iphone || a0.ipad);
class QA {
  /**
   * 测试保存音频或播放音频
   */
  //saveBufList = [];
  constructor(e = 1, t = 8e3, i) {
    y(this, "renderType", Td.PCMRender);
    y(this, "TAG");
    y(this, "channels");
    y(this, "sampleRate");
    y(this, "volume", 1);
    y(this, "playbackRate", 1);
    y(this, "bufferSource");
    y(this, "eventCallback");
    y(this, "startTime", -1);
    y(this, "callbackInterval");
    y(this, "numQueue", new KA());
    y(this, "audioCtx");
    y(this, "gainNode");
    y(this, "audioResample");
    y(this, "callbackWatcher", () => {
      if (!this.eventCallback) return;
      let e = this.audioCtx;
      if (!e) return;
      const t = e.currentTime, i = this.numQueue.fetch(t);
      Number.isInteger(i) && this.eventCallback(i);
    });
    y(this, "playAudioBuffer", (e, t) => {
      try {
        const i = this.playbackRate;
        let s = e.duration / this.channels / i, n = this.audioCtx;
        if (!n) return;
        let a = this.startTime, o = n.currentTime;
        (a < 0 || a < o) && (a = o);
        const c = 1e6;
        this.startTime = (a * c + s * c) / c, this.numQueue.push(a, t);
        const l = 44100;
        if (this.sampleRate !== l && Ef) {
          const { numberOfChannels: d, sampleRate: h } = e;
          this.audioResample || (this.audioResample = new jA({
            src: {
              codec: Ca(ae.PCM),
              codecType: ae.PCM,
              channelCount: d,
              audioSampleRate: h
            },
            dist: {
              codec: Ca(ae.PCM),
              codecType: ae.PCM,
              channelCount: d,
              audioSampleRate: l
            }
          })), this.audioResample.resampleAudioBuffer(e).then((u) => {
            this.playAtTime(u, a);
          });
        } else
          this.playAtTime(e, a);
      } catch {
      }
    });
    if (this.TAG = S.traceTag(this.renderType, i), this.channels = e, this.sampleRate = t, this.callbackInterval = setInterval(this.callbackWatcher, 20), Ef) {
      const s = () => {
        var n;
        try {
          this.init(), (n = this.audioCtx) == null || n.resume(), document.removeEventListener("touchend", s), document.removeEventListener("touchstart", s), document.removeEventListener("click", s);
        } catch (a) {
          S.e(this.TAG, "onCanPlay", (a == null ? void 0 : a.message) || (a == null ? void 0 : a.stack) || (a == null ? void 0 : a.toString()));
        }
      };
      document.addEventListener("touchstart", s), document.addEventListener("touchend", s), document.addEventListener("click", s);
    } else
      this.init();
  }
  init() {
    let e = this.audioCtx;
    if (!e) {
      e = this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
      try {
        const t = this.gainNode = e.createGain();
        this.setVolume(this.volume), t.connect(e.destination);
      } catch (t) {
        S.e(this.TAG, "init error ", (t == null ? void 0 : t.message) || (t == null ? void 0 : t.stack) || (t == null ? void 0 : t.toString()));
      }
    }
  }
  getVolume() {
    return this.volume || 0;
  }
  setPlaybackRate(e) {
    e !== this.playbackRate && (this.playbackRate = e);
  }
  getPlaybackRate() {
    return this.playbackRate;
  }
  setVolume(e) {
    var t, i;
    this.volume = e, this.gainNode && this.gainNode.gain.value !== this.volume && (this.gainNode.gain.value = this.volume, (i = (t = this.gainNode.gain).setValueAtTime) == null || i.call(t, this.volume, 0));
  }
  destroy() {
    S.d(this.TAG, "call destroy"), this.eventCallback = void 0, clearInterval(this.callbackInterval), this.numQueue.clear(), this.gainNode && this.gainNode.disconnect(), this.bufferSource && (this.bufferSource.stop(), this.bufferSource.disconnect(), this.bufferSource = void 0), this.close(), this.audioCtx = void 0, this.audioResample && (this.audioResample.destroy(), this.audioResample = void 0), this.startTime = -1;
  }
  close() {
    var e;
    (e = this.audioCtx) == null || e.close();
  }
  renderFrame(e, t) {
    let i = this.channels;
    if (!(!i || !this.sampleRate || !e.length || !this.audioCtx))
      try {
        this.init();
        const s = {
          data: e,
          dts: 0,
          duration: 0
        }, n = {
          codec: Ca(ae.PCM),
          audioSampleRate: this.sampleRate,
          channelCount: i,
          codecType: ae.PCM
        }, a = Cg(s, n, this.audioCtx);
        this.playAudioBuffer(a, t);
      } catch {
      }
  }
  playAtTime(e, t) {
    let i = this.audioCtx;
    if (!i) return;
    let s = this.bufferSource = i.createBufferSource();
    s.buffer = e, s.playbackRate.value = this.playbackRate, s.connect(this.gainNode), this.setVolume(this.volume), s.start ? s.start(t) : s.play ? s.play(t) : s.noteOn && s.noteOn(t);
  }
  stop() {
    this.destroy();
  }
}
const Sf = self.MediaStreamTrackGenerator;
class Tf extends ve {
  /**
   *Creates an instance of WCSVideoRender.
   * @param {*} config
   * @memberof WCSVideoRender
   */
  constructor(t) {
    super();
    y(this, "renderType", Sd.WCSVideoRender);
    y(this, "TAG");
    y(this, "renderContainer");
    y(this, "mediaElement");
    y(this, "mediaElementStreamWriter");
    y(this, "lastRenderTime", 0);
    y(this, "_onvCanPlay", () => {
      S.d(this.TAG, "_onvCanPlay");
      const t = this.mediaElement;
      if (t) {
        if (t.removeEventListener("canplay", this._onvCanPlay), t.autoplay) {
          let i = t.play();
          i !== void 0 && i.then(() => {
          }).catch((s) => {
            S.e(this.TAG, "Events.CAN_PLAY canot autoplay！", (s == null ? void 0 : s.message) || (s == null ? void 0 : s.stack) || (s == null ? void 0 : s.toString())), this.pause();
          });
        }
        this.emit(z.CAN_PLAY);
      }
    });
    const { videoRenderWrapperId: i, traceId: s } = t;
    this.TAG = S.traceTag(this.renderType, s), this.renderContainer = document.querySelector("#" + i), this.createVideo();
  }
  static isSupport() {
    return je.supportVideoDecoder() && !!Sf;
  }
  getRender() {
    return this.mediaElement;
  }
  resetVideo() {
    var i;
    const t = this.mediaElement;
    t && (t.pause(), (i = this.mediaElementStreamWriter) == null || i.close(), this.mediaElementStreamWriter = void 0, t.srcObject = null, t.load());
  }
  createVideo(t = 0, i = 0) {
    var a, o;
    let s = this.mediaElement = (a = this.renderContainer) == null ? void 0 : a.querySelector("video");
    s || (s = this.mediaElement = document.createElement("video"), s.autoplay = !0, s.addEventListener("canplay", this._onvCanPlay), (o = this.renderContainer) == null || o.appendChild(s)), s.setAttribute("render-type", this.renderType), s.style.display = "block";
    const n = [];
    if (!this.mediaElementStreamWriter) {
      const c = new Sf({
        kind: "video"
      });
      this.mediaElementStreamWriter = c.writable.getWriter(), n.push(c);
    }
    return n.length && (s.srcObject = new MediaStream(n), s.load()), s.width = t, s.height = i, s;
  }
  pause() {
    var t;
    (t = this.mediaElement) == null || t.pause(), this.emit(z.PLAYER_PAUSE);
  }
  play() {
    var t;
    (t = this.mediaElement) == null || t.play();
  }
  destroyVideo() {
    const t = this.mediaElement;
    t && (this.resetVideo(), t.style.display = "none", this.mediaElement = void 0);
  }
  async renderFrame(t) {
    var a;
    const { codedWidth: i, codedHeight: s } = t;
    this.createVideo(i, s);
    const n = Qi();
    if (this.lastRenderTime && n - this.lastRenderTime < 50) return t.close();
    (a = this.mediaElementStreamWriter) == null || a.write(t).catch((o) => {
      S.e(this.TAG, "video stream write error ", (o == null ? void 0 : o.message) || (o == null ? void 0 : o.stack) || (o == null ? void 0 : o.toString())), this.resetVideo();
    }), this.lastRenderTime = n, t.close();
  }
  destroy() {
    this.removeAllListeners(), this.destroyVideo();
  }
}
class bf extends ve {
  /**
   *Creates an instance of WCSCanvasRender.
   * @param {*} streamId
   * @param {*} config
   * @memberof WCSCanvasRender
   */
  constructor(t) {
    super();
    y(this, "renderType", Sd.WCSCanvasRender);
    // private TAG: string;
    y(this, "renderContainer");
    y(this, "canvas");
    y(this, "config");
    y(this, "ctx");
    y(this, "lastRenderTime");
    const {
      videoRenderWrapperId: i
      /* traceId */
    } = this.config = t;
    this.renderContainer = document.querySelector("#" + i);
  }
  static isSupport() {
    return !!je.supportVideoDecoder();
  }
  getRender() {
    return this.canvas;
  }
  createCanvas(t, i) {
    var a;
    let s = this.canvas;
    s || (s = this.canvas = document.createElement("canvas"), s.setAttribute("render-type", this.renderType), (a = this.renderContainer) == null || a.appendChild(s));
    const { numOfMultiscreen: n = 1 } = this.config || {};
    return s.width = t / n, s.height = i / n, this.ctx = s.getContext("2d", { alpha: !1 }), s;
  }
  destroyCanvas() {
    var i, s;
    const t = (i = this.renderContainer) == null ? void 0 : i.querySelector("canvas");
    t && (this.canvas = void 0, (s = this.renderContainer) == null || s.removeChild(t));
  }
  renderFrame(t) {
    var a;
    const i = Qi();
    if (this.lastRenderTime && i - this.lastRenderTime < 50) return t.close();
    const { codedWidth: s, codedHeight: n } = t;
    (!this.canvas || this.canvas.width !== s || this.canvas.height !== n) && this.createCanvas(s, n), this.canvas && ((a = this.ctx) == null || a.drawImage(t, 0, 0, this.canvas.width, this.canvas.height), this.lastRenderTime = i), t.close();
  }
  destroy() {
    this.destroyCanvas(), this.ctx = null, this.config = void 0;
  }
}
const Rg = 4096, JA = 1.1, qA = 1.05, Af = 300, yi = {
  /**
   * 1 范围内
   */
  NONE: 1,
  /**
   * 2 视频快
   */
  VIDEO_QUICKLY: 2,
  /**
   * 3 音频快
   */
  AUDIO_QUICKLY: 3
};
class e3 extends ve {
  constructor(t) {
    const { videoDecoderConstructor: i, audioDecoderConstructor: s, config: n, videoMeta: a, audioMeta: o } = t;
    super();
    y(this, "TAG");
    y(this, "config");
    y(this, "isGoodDecoder", !1);
    y(this, "videoMeta");
    y(this, "audioMeta");
    y(this, "audioCacheTime");
    y(this, "videoDecoder");
    y(this, "audioDecoder");
    y(this, "audioRender");
    y(this, "videoRender");
    y(this, "volume");
    y(this, "videoTimer");
    y(this, "videoPlayDelayTimer");
    y(this, "staticFrameInterval");
    y(this, "seekTimer");
    y(this, "lastTime", 0);
    y(this, "lastTimeout", 0);
    y(this, "isPause", !1);
    y(this, "isDestroy", !1);
    y(this, "isSeek", !1);
    y(this, "isLive", !0);
    y(this, "playbackRate", 1);
    y(this, "videoPlaybackRate", 1);
    y(this, "fromPlaybackRate4", !1);
    y(this, "decodeVideoStatistics", []);
    y(this, "audioPlayCurrentTime", 0);
    y(this, "playCurrentDts", 0);
    y(this, "videoPlayQuickly", !1);
    y(this, "avSyncStatus", yi.NONE);
    y(this, "videoTrack");
    y(this, "audioTrack");
    y(this, "firstVideoFrame", !0);
    y(this, "firstAudioFrame", !0);
    y(this, "staticFrameDts", 0);
    y(this, "staticFrameTimestamp", 0);
    y(this, "onDecodeError", (t) => this.emit(z.ERROR, t));
    y(this, "onVideoFrame", (t) => {
      let { data: i, time: s, isKeyframe: n } = t;
      i && this.videoRender && (this.decodeVideoStatistics.push({
        decodeTime: s,
        isKeyframe: n
      }), setTimeout(this._emitDecodeVideoStatistics, 0), this.videoRender.renderFrame(i), this.firstVideoFrame && (this.firstVideoFrame = !1, S.k(this.TAG, "render first video")));
    });
    y(this, "onAudioFrame", (t, i) => {
      let { data: s, timestamp: n } = t;
      const a = this.audioRender, o = this.audioDecoder;
      o && (o == null ? void 0 : o.decoderType) === Mt.WCSAudioDecoder && (a == null ? void 0 : a.renderType) === Td.PCMRender && (s = s.map((c) => o.toBuffer(c)), i || (i = s.reduce((c, l) => c + l.length, 0))), a == null || a.renderFrame(ui(...s), n), this.firstAudioFrame && (this.firstAudioFrame = !1, S.k(this.TAG, "render first audio"));
    });
    /**
     * 视音频播放check
     * @returns
     */
    y(this, "checkPlay", () => {
      if (this.isPause || this.isDestroy)
        return;
      const t = this.videoTrack, i = this.audioTrack;
      let s = t == null ? void 0 : t.canPlay(), n = i == null ? void 0 : i.canPlay();
      const a = this.audioPlayCurrentTime;
      if (t && i && n && a > 0 && this.config.enableAVSync) {
        const { currenTime: o } = i;
        let c = t.currenTime;
        if (o - a > this.audioCacheTime && (n = !1), c > 0 && this.playbackRate == 1) {
          const l = a - c, d = Math.abs(l);
          l > Af ? (this.avSyncStatus !== yi.AUDIO_QUICKLY && (this.avSyncStatus = yi.AUDIO_QUICKLY, S.i(this.TAG, `[avsync] audio play quickly  vtime=${c} atime=${a}`)), this.videoPlaybackRate = JA) : c - a > Af ? this.avSyncStatus !== yi.VIDEO_QUICKLY && (this.avSyncStatus = yi.VIDEO_QUICKLY, S.i(this.TAG, `[avsync] video play quickly vtime=${c} atime=${a}`)) : d <= 100 && (this.avSyncStatus !== yi.NONE && (this.avSyncStatus = yi.NONE, S.i(this.TAG, "[avsync] play normal")), this.videoPlaybackRate = this.playbackRate);
        }
      }
      n && this.audioPlay(), s && (s = !i || this.avSyncStatus !== yi.VIDEO_QUICKLY), s && (t == null || t.playStart(), this.videoPlay());
    });
    y(this, "audioCallback", (t) => {
      this.audioPlayCurrentTime = t, this.videoTrack || this.eventCallback(0, t), setTimeout(this.checkPlay, 0);
    });
    y(this, "videoCallback", () => {
      var t;
      (t = this.videoTrack) == null || t.playStop(), this.checkPlay();
    });
    y(this, "_emitDecodeVideoStatistics", () => {
      const t = this.decodeVideoStatistics, i = t.reduce((n, a) => n + a.decodeTime, 0), s = t.length;
      if (i >= 5 * Zt || s >= 100) {
        const { IFrame: n, IFrameCount: a } = t.reduce(
          (o, { isKeyframe: c, decodeTime: l }) => (c && (o.IFrame += l, o.IFrameCount += 1), o),
          { IFrame: 0, IFrameCount: 0 }
        );
        this.emit(z.WCS_STATISTICS_INFO, {
          type: "decodeFrequency",
          data: {
            frequency: Math.floor(s / (i / Zt)),
            IFrame: Math.round(n),
            IFrameCount: a
          }
        }), this.decodeVideoStatistics = [];
      }
    });
    y(this, "videoPlay", async () => {
      clearInterval(this.staticFrameInterval);
      const t = this.videoTrack;
      if (this.isPause || this.isDestroy || this.isSeek) {
        S.w(this.TAG, "_video playStop!!"), t == null || t.playStop();
        return;
      }
      if (this.checkDataAccumulation() || !t)
        return;
      const i = t == null ? void 0 : t.nextFrame();
      if (!i) {
        const { currentFrame: m } = t;
        clearTimeout(this.videoPlayDelayTimer), this.videoPlayDelayTimer = setTimeout(this.videoCallback, m.duration);
        return;
      }
      const s = Qi();
      let { isStaticFrame: n, ipcamTime: a } = i.extras;
      const o = i.isKeyframe;
      let c = !this.fromPlaybackRate4 && this.playbackRate < 4;
      (o || c) && (await this.decodeVideoFrame(i, !0), o && (this.fromPlaybackRate4 = !1, this.clearTrackBuffer(t, i.dts))), a = a || -1;
      const l = i.dts;
      if (this.eventCallback(0, l, a, o), n) {
        S.d(this.TAG, `staticFrame=${n}, frameDts=${l}, ipcamTime=${a}`), this.staticFrameDts = l, this.staticFrameTimestamp = a;
        const m = 100;
        this.staticFrameInterval = setInterval(() => {
          const g = m * this.playbackRate;
          this.staticFrameDts += g, this.staticFrameTimestamp += g, this.eventCallback(0, this.staticFrameDts, this.staticFrameTimestamp, o);
        }, m);
      }
      let d = i.duration;
      d /= this.videoPlaybackRate;
      const h = Qi(), u = h - s, f = this.lastTime ? s - this.lastTime : 0;
      let p = d - u - (f - this.lastTimeout);
      p = Math.min(d, Math.max(0, p)), this.videoTimer = setTimeout(this.videoCallback, p), this.lastTime = h, this.lastTimeout = p;
    });
    const { isLive: c = !0, traceId: l, liveBufferMS: d } = this.config = n;
    this.TAG = S.traceTag("WCSPlayer", l), this.videoMeta = a, this.audioMeta = o, this.isLive = c, this.audioCacheTime = (o == null ? void 0 : o.codecType) === ae.AAC ? 256 : 200;
    let h = { startPlay: d };
    if (i && a) {
      const u = this.videoDecoder = new i(a, n);
      u.on("data", this.onVideoFrame), u.on("error", this.onDecodeError), this.isGoodDecoder = u.decoderType === Mt.WCSVideoDecoder, this.createVideoRender(), this.videoTrack = new vf(jt.Video, h, l);
    }
    if (s && o) {
      const u = this.audioDecoder = new s(o, n);
      u.on("data", this.onAudioFrame), u.on("error", this.onDecodeError), this.createAudioRender(), this.audioTrack = new vf(jt.Audio, h, l);
    }
  }
  destroy() {
    var t, i, s, n;
    this.stop(), (t = this.videoRender) == null || t.destroy(), this.videoRender = void 0, (i = this.audioRender) == null || i.destroy(), this.audioRender = void 0, (s = this.videoDecoder) == null || s.destroy(), this.videoDecoder = void 0, (n = this.audioDecoder) == null || n.destroy(), this.audioDecoder = void 0;
  }
  play(t, i, s, n, a = !0, o) {
    let c;
    if (s && (c = new Uint8Array(s), a)) {
      const u = new Uint8Array(c.length);
      u.set(c, 0), c = u;
    }
    let l = new $A(c, t, n, o), d = t < Rg;
    d && (i ? l.isKeyframe = i : l.checkVideoKeyFrame());
    let h = d ? this.videoTrack : this.audioTrack;
    h == null || h.add(l), this.checkPlay();
  }
  getVolume() {
    var t;
    return this.volume = (t = this.audioRender) == null ? void 0 : t.getVolume(), this.volume || 0;
  }
  setVolume(t = 0) {
    var i;
    this.volume = t, (i = this.audioRender) == null || i.setVolume(t);
  }
  resume() {
    this.isSeek || !this.isPause || this.seek(this.playCurrentDts || 0);
  }
  doResume() {
    this.isPause = !1, this.checkPlay();
  }
  getVideoRender() {
    var t;
    return (t = this.videoRender) == null ? void 0 : t.getRender();
  }
  getAudioRender() {
    return this.audioRender;
  }
  getMetaDataInfo() {
    return {
      video: this.videoMeta,
      audio: this.audioMeta
    };
  }
  get paused() {
    return this.isPause;
  }
  get duration() {
    var t;
    return ((t = this.videoTrack || this.audioTrack) == null ? void 0 : t.duration) ?? 0;
  }
  get buffered() {
    var t;
    return (t = this.videoTrack || this.audioTrack) == null ? void 0 : t.buffered;
  }
  pause() {
    var t, i, s;
    this.isPause || (this.isPause = !0, (t = this.videoTrack) == null || t.playStop(), (i = this.audioTrack) == null || i.playStop(), clearTimeout(this.videoTimer), (s = this.audioRender) == null || s.stop(), this.audioRender = void 0);
  }
  seek(t, i) {
    var a, o;
    if (this.isLive || this.isSeek) return;
    this.avSyncStatus = yi.NONE, clearTimeout(this.videoTimer), this.lastTime = 0, this.lastTimeout = 0, this.pause(), this.isSeek = !0;
    let s = this.videoTrack;
    if (s) {
      const c = s.seek(t);
      S.d(this.TAG, `seek to ${t},will deocde ${c.length} frame`), c.forEach((d) => {
        S.d(this.TAG, `seek deocde frame dts=${d.dts} keyframe=${d.isKeyframe}`), this.decodeVideoFrame(d, !1);
      });
      const { currentFrame: l } = s;
      (o = this.eventCallback) == null || o.call(this, 0, l.dts, (a = l.extras) == null ? void 0 : a.ipcamTime);
    }
    const n = this.audioTrack;
    n && (n.seek(t), n.playStop(), this.createAudioRender()), this.isSeek = !1, this.doResume(), i && i();
  }
  stop() {
    var t, i, s, n;
    this.avSyncStatus = yi.NONE, clearTimeout(this.videoPlayDelayTimer), clearInterval(this.staticFrameInterval), this.videoTimer && ((t = this.videoTrack) == null || t.playStop(), clearTimeout(this.videoTimer), this.videoTimer = void 0), this.seekTimer && (clearInterval(this.seekTimer), this.seekTimer = void 0), (i = this.audioRender) == null || i.stop(), (s = this.videoTrack) == null || s.clear(), (n = this.audioTrack) == null || n.clear(), this.isPause = !1, this.isSeek = !1, this.isDestroy = !0, this.lastTime = 0, this.lastTimeout = 0;
  }
  setMuted(t) {
    S.d(this.TAG, `setMuted ${t}`);
  }
  setPlaybackRate(t) {
    var i;
    this.playbackRate !== t && (this.fromPlaybackRate4 = this.playbackRate === 4 && this.playbackRate !== t, this.playbackRate = t, this.videoPlaybackRate = t, (i = this.audioRender) == null || i.setPlaybackRate(t));
  }
  eventCallback(t, i, s, n) {
    this.isSeek || (s = Math.max(0, s || 0), this.playCurrentDts = i, isNaN(s) && (s = i), this.emit(z.TIME_UPDATE, { code: t, dts: i, ipcamTime: s, isSync: n }));
  }
  createVideoRender() {
    var i, s, n;
    if (this.videoRender) return;
    let t;
    ((i = this.videoDecoder) == null ? void 0 : i.decoderType) === Mt.WCSVideoDecoder && (Tf.isSupport() ? t = Tf : bf.isSupport() && (t = bf)), t && (this.videoRender = new t(this.config), (n = (s = this.videoRender).on) == null || n.call(s, z.PLAYER_PAUSE, (...a) => this.emit(z.PLAYER_PAUSE, ...a)));
  }
  createAudioRender() {
    let t = this.audioRender;
    if (t) return;
    const { channelCount: i, audioSampleRate: s } = this.audioMeta;
    t = new QA(i, s, this.config.traceId), t && (this.audioRender = t, t.eventCallback = this.audioCallback), this.setPlaybackRate(this.playbackRate), this.setVolume(this.volume), this.audioPlayCurrentTime = 0;
  }
  audioPlay() {
    var c;
    if (this.isPause) return;
    const t = this.audioMeta, i = this.audioTrack;
    let s = i == null ? void 0 : i.nextFrame();
    if (!(s != null && s.data) || !t) return;
    const n = {
      dts: s.dts,
      data: s.data,
      duration: s.duration
    };
    (c = this.audioDecoder) == null || c.decode(n, !0);
    const a = this.videoTrack, o = (a == null ? void 0 : a.gopDuration) || 4 * Zt;
    i && this.clearTrackBuffer(i, i.currenTime - o - Zt), setTimeout(this.checkPlay, 0);
  }
  /**
   * 解码能力不足时，会造成数据堆积，直播时需要做追赶，避免高延时
   * 大于设置的缓存时长，且大于1个GOP以上时，做追赶
   */
  checkDataAccumulation() {
    if (!this.isLive) return !1;
    const t = this.videoTrack;
    if (!t) return;
    let { remain: i, newestKeyframe: s, lastKeyframe: n, gopDuration: a, duration: o, currentFrame: c } = t;
    if (!s || !n) return !1;
    let l;
    const d = s.dts;
    if (i > a) {
      if (s === n) return !1;
      l = d;
    } else if (this.isGoodDecoder) {
      const { liveBufferMS: u = 0 } = this.config, f = u, p = f + _c;
      if (s !== n) {
        const m = o - d;
        if (m < p + _c || m > i || i < p) return !1;
        l = d;
      } else {
        let m = this.videoPlayQuickly;
        if (m) {
          const g = t.nextFrame(!0);
          m = i > f && !!g;
        } else
          m = i > p;
        if (m !== this.videoPlayQuickly) {
          this.setPlaybackRate(m ? qA : 1);
          const g = m ? "start" : "completed";
          S.d(
            this.TAG,
            `video play quickly ${g}, playbackRate = ${this.playbackRate} remain=${i} videoPlayQuickly=${m} current dts=${c.dts}`
          ), this.videoPlayQuickly = m;
        }
        return !1;
      }
    }
    if (!l) return !1;
    const h = `too much video data, seek to ${l}ms, gopDuration=${a}ms,remain=${i},duration:${o} keyframe.dts=${d}  current dts=${c.dts}`;
    return S.i(this.TAG, h), this.videoPlayQuickly = !1, this.setPlaybackRate(1), this.seek(l), t.playStop(), !0;
  }
  /**
   *长时间播放，内存上涨，清理播放过的数据
   *
   * @memberof WCSPlayer
   */
  clearTrackBuffer(t, i) {
    t.clearBeforeTime(i, this.isLive);
  }
  async decodeVideoFrame(t, i = !1) {
    if (!(t != null && t.data)) return null;
    const { dts: s, data: n, isKeyframe: a, duration: o, extras: c } = t, l = this.videoMeta, { videoMeta: d } = c || {}, h = this.videoDecoder, u = (h == null ? void 0 : h.decoderType) === Mt.WasmVideoDecoder;
    if (a) {
      if (S.d(this.TAG, `video key frame decode, dts=${s}`), d && (l == null ? void 0 : l.codecType) !== (d == null ? void 0 : d.codecType)) {
        S.w(this.TAG, `video codec changed,${l == null ? void 0 : l.codecType}->${d == null ? void 0 : d.codecType}`);
        let p = !1;
        if ((h == null ? void 0 : h.decoderType) === Mt.WCSVideoDecoder ? p = await _n.isSupport(d) : u && (d.codecType === de.H264 && je.supportMSEH264Playback() ? p = !1 : p = !0), p)
          h == null || h.reset(d);
        else
          return setTimeout(() => {
            this.emit(z.PLAYER_NEED_RESTART);
          }, 0), null;
      }
      this.videoMeta = d;
    }
    const f = {
      data: n,
      dts: s,
      duration: o,
      isKeyframe: a
    };
    h == null || h.decode(f, i);
  }
}
class Rd extends bg {
  constructor(t, i, s) {
    super(t, i, jt.Audio, s);
    y(this, "isRenderList", []);
    y(this, "bufferList", []);
    y(this, "bufferLength", 0);
    y(this, "audioDecodeStart", (t) => {
      this.decodeStart(t), this.isRenderList.push(t.isRender);
    });
    y(this, "audioDecodeEnd", (t, i, s) => {
      s = s ?? this.isRenderList.shift(), i = i ?? t.length, this.bufferList.push(t), this.bufferLength += i || 0, s ? (super.decodeEnd(this.bufferList, this.bufferLength), this.clearBuffer()) : super.decodeEnd(null);
    });
  }
  clearBuffer() {
    this.bufferList = [], this.bufferLength = 0;
  }
  destroy() {
    super.destroy(), this.isRenderList = [], this.clearBuffer();
  }
}
const Ig = " ", t3 = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)), Cf = typeof self < "u" && self.Blob && new Blob([t3(Ig)], { type: "text/javascript;charset=utf-8" });
function i3(r) {
  let e;
  try {
    if (e = Cf && (self.URL || self.webkitURL).createObjectURL(Cf), !e) throw "";
    const t = new Worker(e, {
      name: r == null ? void 0 : r.name
    });
    return t.addEventListener("error", () => {
      (self.URL || self.webkitURL).revokeObjectURL(e);
    }), t;
  } catch {
    return new Worker(
      "data:text/javascript;base64," + Ig,
      {
        name: r == null ? void 0 : r.name
      }
    );
  } finally {
    e && (self.URL || self.webkitURL).revokeObjectURL(e);
  }
}
const s3 = self.AudioDecoder, r3 = self.EncodedAudioChunk;
class n3 extends ve {
  constructor(t, i) {
    super();
    y(this, "TAG");
    y(this, "decoder");
    y(this, "metaInfo");
    y(this, "isAAC");
    y(this, "decodeQueue", []);
    y(this, "handleDequeue", () => {
      if (this.decodeQueue.length) {
        const t = this.decodeQueue.shift();
        t && this.decodeFrame(t);
      }
    });
    y(this, "handleFrame", (t) => {
      this.emit("data", t);
    });
    y(this, "handleError", (t) => {
      S.e(this.TAG, "handleError ", (t == null ? void 0 : t.message) || (t == null ? void 0 : t.stack) || (t == null ? void 0 : t.toString())), this.emit("error", t);
    });
    this.TAG = S.traceTag("WCSAudioDecoderImpl", i), this.metaInfo = t, this.isAAC = t.codec == ae.AAC;
  }
  decode(t) {
    const { data: i, dts: s, duration: n = 0 } = t;
    let a = this.decoder;
    if (!a) {
      let { codec: l, channelCount: d, audioSampleRate: h } = this.metaInfo;
      if (this.isAAC) {
        d = i[3] === 64 ? 1 : 2;
        const u = i[2] >> 2 & 15;
        h = Eg[u];
      }
      a = this.decoder = new s3({
        output: this.handleFrame,
        error: this.handleError
      }), a.addEventListener && a.addEventListener("dequeue", this.handleDequeue), a.configure({ codec: l, numberOfChannels: d, sampleRate: h });
    }
    let o = i;
    this.isAAC && (o = new Uint8Array(i).slice(7));
    const c = new r3({
      timestamp: s * 1e3,
      type: "key",
      data: o,
      duration: n * 1e3
    });
    a != null && a.addEventListener && (a.decodeQueueSize > 0 || this.decodeQueue.length) ? this.decodeQueue.push(c) : this.decodeFrame(c);
  }
  decodeFrame(t) {
    var i, s, n;
    if (((i = this.decoder) == null ? void 0 : i.state) !== "configured") {
      console.warn(this.TAG, "decodeFrame  state=" + ((s = this.decoder) == null ? void 0 : s.state)), this.emit("error", { type: "stateerror", message: `${this.TAG} audio state=${(n = this.decoder) == null ? void 0 : n.state}` });
      return;
    }
    this.decoder.decode(t);
  }
  destroy() {
    this.removeAllListeners(), this.decodeQueue = [];
    let t = this.decoder;
    t && (t.state !== "closed" && t.close(), t = this.decoder = void 0);
  }
}
const Rf = self.AudioDecoder, uo = class uo extends Rd {
  constructor(t, i) {
    const { enableAudioWorker: s, traceId: n } = i;
    super(Mt.WCSAudioDecoder, t.codecType, n);
    y(this, "isAAC");
    y(this, "worker");
    y(this, "decoder");
    y(this, "onWorkerMessage", (t) => {
      let i = t.data, s = i.data;
      switch (i.msg) {
        case "data":
          this.audioDecodeEnd(s);
          break;
        case "error":
          this.decodeError(t);
          break;
      }
    });
    this.isAAC = t.codecType === ae.AAC;
    const a = Us.DecodeWCSVideo;
    if (s && typeof Worker < "u" && _s.isSupport(a))
      try {
        this.worker = new _s(new i3(), a, n), this.worker.onWorkerMessage = this.onWorkerMessage, this.worker.init(t, n);
      } catch (o) {
        S.e(this.TAG, "Error while initialize WCSAudioDecoder worker, fallback to inline WCSAudioDecoder", (o == null ? void 0 : o.message) || (o == null ? void 0 : o.stack) || (o == null ? void 0 : o.toString())), this.worker = void 0;
      }
    if (!this.worker) {
      const o = this.decoder = new n3(t, n);
      o.on("data", this.audioDecodeEnd), o.on("error", this.decodeError);
    }
  }
  static getConfig(t) {
    const { codec: i, channelCount: s, audioSampleRate: n } = t;
    return {
      codec: i,
      sampleRate: n,
      numberOfChannels: s
    };
  }
  static async isSupport(t) {
    if (!Rf) return !1;
    const i = uo.getConfig(t);
    try {
      const { supported: s } = await Rf.isConfigSupported(i);
      return s;
    } catch {
      return !1;
    }
  }
  decode(t, i) {
    var a;
    const { dts: s, duration: n } = t;
    this.isAAC && (i = !0), this.audioDecodeStart({ isRender: i, dts: s, isKeyframe: !1, duration: n }), this.worker ? this.worker.postMessage(
      { cmd: "decode", data: t }
      /* , [data.buffer] */
    ) : (a = this.decoder) == null || a.decode(t);
  }
  toBuffer(t) {
    return YA(t);
  }
  destroy() {
    var t;
    super.destroy(), this.worker ? this.worker.destroy() : ((t = this.decoder) == null || t.destroy(), this.decoder = void 0);
  }
};
y(uo, "CLASSNAME", Mt.WCSAudioDecoder);
let qa = uo;
const If = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  36,
  40,
  44,
  48,
  52,
  56,
  64,
  72,
  80,
  88,
  96,
  108,
  120,
  132,
  144,
  156,
  172,
  188,
  212,
  240,
  276,
  320,
  384,
  448,
  512,
  576,
  640,
  704,
  768,
  832,
  896,
  960,
  1024
]), Lf = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  32,
  40,
  48,
  64,
  92,
  128
]), a3 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  36,
  40,
  44,
  48,
  52,
  56,
  64,
  72,
  80,
  88,
  100,
  112,
  124,
  140,
  156,
  172,
  192,
  216,
  240,
  268,
  304,
  344,
  384,
  424,
  464,
  504,
  544,
  584,
  624,
  664,
  704,
  744,
  784,
  824,
  864,
  904,
  944,
  984,
  1024
]), o3 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  32,
  40,
  48,
  64,
  92,
  128
]), Df = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  36,
  40,
  48,
  56,
  64,
  72,
  80,
  88,
  96,
  108,
  120,
  132,
  144,
  160,
  176,
  196,
  216,
  240,
  264,
  292,
  320,
  352,
  384,
  416,
  448,
  480,
  512,
  544,
  576,
  608,
  640,
  672,
  704,
  736,
  768,
  800,
  832,
  864,
  896,
  928,
  1024
]), o0 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  28,
  36,
  44,
  56,
  68,
  80,
  96,
  112,
  128
]), l3 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  36,
  40,
  48,
  56,
  64,
  72,
  80,
  88,
  96,
  108,
  120,
  132,
  144,
  160,
  176,
  196,
  216,
  240,
  264,
  292,
  320,
  352,
  384,
  416,
  448,
  480,
  512,
  544,
  576,
  608,
  640,
  672,
  704,
  736,
  768,
  800,
  832,
  864,
  896,
  928,
  960,
  992,
  1024
]), Pf = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  36,
  40,
  44,
  52,
  60,
  68,
  76,
  84,
  92,
  100,
  108,
  116,
  124,
  136,
  148,
  160,
  172,
  188,
  204,
  220,
  240,
  260,
  284,
  308,
  336,
  364,
  396,
  432,
  468,
  508,
  552,
  600,
  652,
  704,
  768,
  832,
  896,
  960,
  1024
]), kf = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  36,
  44,
  52,
  64,
  76,
  92,
  108,
  128
]), l0 = new Uint16Array([
  0,
  8,
  16,
  24,
  32,
  40,
  48,
  56,
  64,
  72,
  80,
  88,
  100,
  112,
  124,
  136,
  148,
  160,
  172,
  184,
  196,
  212,
  228,
  244,
  260,
  280,
  300,
  320,
  344,
  368,
  396,
  424,
  456,
  492,
  532,
  572,
  616,
  664,
  716,
  772,
  832,
  896,
  960,
  1024
]), c0 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  32,
  40,
  48,
  60,
  72,
  88,
  108,
  128
]), c3 = new Uint16Array([
  0,
  12,
  24,
  36,
  48,
  60,
  72,
  84,
  96,
  108,
  120,
  132,
  144,
  156,
  172,
  188,
  204,
  220,
  236,
  252,
  268,
  288,
  308,
  328,
  348,
  372,
  396,
  420,
  448,
  476,
  508,
  544,
  580,
  620,
  664,
  712,
  764,
  820,
  880,
  944,
  1024
]), d3 = new Uint16Array([
  0,
  4,
  8,
  12,
  16,
  20,
  24,
  28,
  36,
  44,
  52,
  60,
  72,
  88,
  108,
  128
]), h3 = [
  If,
  If,
  a3,
  Df,
  Df,
  l3,
  Pf,
  Pf,
  l0,
  l0,
  l0,
  c3
], u3 = [
  Lf,
  Lf,
  o3,
  o0,
  o0,
  o0,
  kf,
  kf,
  c0,
  c0,
  c0,
  d3
], f3 = new Uint8Array([
  12,
  12,
  12,
  14,
  14,
  14,
  15,
  15,
  15,
  15,
  15,
  15
]), p3 = new Uint8Array([
  41,
  41,
  47,
  49,
  49,
  51,
  47,
  47,
  43,
  43,
  43,
  40
]), m3 = function() {
  let r = new Float32Array(428);
  for (let e = 0; e < 428; e++)
    r[e] = Math.pow(2, (e - 200) / 4);
  return r;
}(), d0 = m3, g3 = function() {
  let r = new Float32Array(8191), e = 4 / 3;
  for (let t = 0; t < 8191; t++)
    r[t] = Math.pow(t, e);
  return r;
}(), wf = g3, Ra = new Int32Array([
  96e3,
  88200,
  64e3,
  48e3,
  44100,
  32e3,
  24e3,
  22050,
  16e3,
  12e3,
  11025,
  8e3,
  7350
]);
let Ac, yn, Ms = self;
function at(r) {
  let e;
  if (r instanceof Uint8Array)
    this.data = r;
  else if (r instanceof ArrayBuffer || Array.isArray(r) || typeof r == "number" || (e = Ms.Buffer) != null && e.isBuffer(r))
    this.data = new Uint8Array(r);
  else if (r.buffer instanceof ArrayBuffer)
    this.data = new Uint8Array(r.buffer, r.byteOffset, r.length * r.BYTES_PER_ELEMENT);
  else if (r instanceof at)
    this.data = r.data;
  else
    throw new Error("Constructing buffer with unknown type.");
  this.length = this.data.length, this.next = null, this.prev = null;
}
at.allocate = function(r) {
  return new at(r);
};
at.prototype.copy = function() {
  return new at(new Uint8Array(this.data));
};
at.prototype.slice = function(r, e) {
  return e == null && (e = this.length), r === 0 && e >= this.length ? new at(this.data) : new at(this.data.subarray(r, r + e));
};
Ac = Ms.BlobBuilder || Ms.MozBlobBuilder || Ms.WebKitBlobBuilder;
yn = Ms.URL || Ms.webkitURL || Ms.mozURL;
at.makeBlob = function(r, e) {
  let t;
  e == null && (e = "application/octet-stream");
  try {
    return new Blob([r], {
      type: e
    });
  } catch (i) {
    console.error(i);
  }
  return Ac != null ? (t = new Ac(), t.append(r), t.getBlob(e)) : null;
};
at.makeBlobURL = function(r, e) {
  return yn != null ? yn.createObjectURL(this.makeBlob(r, e)) : void 0;
};
at.revokeBlobURL = function(r) {
  return yn != null ? yn.revokeObjectURL(r) : void 0;
};
at.prototype.toBlob = function() {
  return at.makeBlob(this.data.buffer);
};
at.prototype.toBlobURL = function() {
  return at.makeBlobURL(this.data.buffer);
};
function Ji() {
  this.first = null, this.last = null, this.numBuffers = 0, this.availableBytes = 0, this.availableBuffers = 0;
}
Ji.prototype.copy = function() {
  let r;
  return r = new Ji(), r.first = this.first, r.last = this.last, r.numBuffers = this.numBuffers, r.availableBytes = this.availableBytes, r.availableBuffers = this.availableBuffers, r;
};
Ji.prototype.append = function(r) {
  let e;
  return r.prev = this.last, (e = this.last) != null && (e.next = r), this.last = r, this.first == null && (this.first = r), this.availableBytes += r.length, this.availableBuffers++, this.numBuffers++;
};
Ji.prototype.advance = function() {
  return this.first ? (this.availableBytes -= this.first.length, this.availableBuffers--, this.first = this.first.next, this.first != null) : !1;
};
Ji.prototype.rewind = function() {
  let r;
  return this.first && !this.first.prev ? !1 : (this.first = ((r = this.first) != null ? r.prev : void 0) || this.last, this.first && (this.availableBytes += this.first.length, this.availableBuffers++), this.first != null);
};
Ji.prototype.reset = function() {
  let r;
  for (r = []; this.rewind(); )
    ;
  return r;
};
function Mn() {
  this.name = "UnderflowError", this.stack = new Error().stack;
}
let qi, Id, Ld, xn, Dd, Pd, kd, wd, Md, Bd, Fd, Vs, Ws;
qi = new ArrayBuffer(16);
Ws = new Uint8Array(qi);
Md = new Int8Array(qi);
Fd = new Uint16Array(qi);
kd = new Int16Array(qi);
Vs = new Uint32Array(qi);
wd = new Int32Array(qi);
Ld = new Float32Array(qi);
typeof Float64Array < "u" && Float64Array !== null && (xn = new Float64Array(qi));
Bd = new Uint16Array(new Uint8Array([18, 52]).buffer)[0] === 13330;
function he(r) {
  this.list = r, this.localOffset = 0, this.offset = 0;
}
he.fromBuffer = function(r) {
  let e;
  return e = new Ji(), e.append(r), new he(e);
};
he.prototype.copy = function() {
  let r;
  return r = new he(this.list.copy()), r.localOffset = this.localOffset, r.offset = this.offset, r;
};
he.prototype.available = function(r) {
  return r <= this.list.availableBytes - this.localOffset;
};
he.prototype.remainingBytes = function() {
  return this.list.availableBytes - this.localOffset;
};
he.prototype.advance = function(r) {
  if (!this.available(r))
    throw new Mn();
  for (this.localOffset += r, this.offset += r; this.list.first && this.localOffset >= this.list.first.length; )
    this.localOffset -= this.list.first.length, this.list.advance();
  return this;
};
he.prototype.rewind = function(r) {
  if (r > this.offset)
    throw new Mn();
  for (this.list.first || (this.list.rewind(), this.localOffset = this.list.first.length), this.localOffset -= r, this.offset -= r; this.list.first.prev && this.localOffset < 0; )
    this.list.rewind(), this.localOffset += this.list.first.length;
  return this;
};
he.prototype.seek = function(r) {
  if (r > this.offset)
    return this.advance(r - this.offset);
  if (r < this.offset)
    return this.rewind(this.offset - r);
};
he.prototype.readUInt8 = function() {
  let r;
  if (!this.available(1))
    throw new Mn();
  return r = this.list.first.data[this.localOffset], this.localOffset += 1, this.offset += 1, this.localOffset === this.list.first.length && (this.localOffset = 0, this.list.advance()), r;
};
he.prototype.peekUInt8 = function(r) {
  let e;
  if (r == null && (r = 0), !this.available(r + 1))
    throw new Mn();
  for (r = this.localOffset + r, e = this.list.first; e; ) {
    if (e.length > r)
      return e.data[r];
    r -= e.length, e = e.next;
  }
  return 0;
};
he.prototype.read = function(r, e) {
  let t, i, s, n;
  if (e == null && (e = !1), e === Bd)
    for (t = i = 0, n = r; i < n; t = i += 1)
      Ws[t] = this.readUInt8();
  else
    for (t = s = r - 1; s >= 0; t = s += -1)
      Ws[t] = this.readUInt8();
};
he.prototype.peek = function(r, e, t) {
  let i, s, n, a, o;
  if (t == null && (t = !1), t === Bd)
    for (i = s = 0, a = r; s < a; i = s += 1)
      Ws[i] = this.peekUInt8(e + i);
  else
    for (i = n = 0, o = r; n < o; i = n += 1)
      Ws[r - i - 1] = this.peekUInt8(e + i);
};
he.prototype.readInt8 = function() {
  return this.read(1), Md[0];
};
he.prototype.peekInt8 = function(r) {
  return r == null && (r = 0), this.peek(1, r), Md[0];
};
he.prototype.readUInt16 = function(r) {
  return this.read(2, r), Fd[0];
};
he.prototype.peekUInt16 = function(r, e) {
  return r == null && (r = 0), this.peek(2, r, e), Fd[0];
};
he.prototype.readInt16 = function(r) {
  return this.read(2, r), kd[0];
};
he.prototype.peekInt16 = function(r, e) {
  return r == null && (r = 0), this.peek(2, r, e), kd[0];
};
he.prototype.readUInt24 = function(r) {
  return r ? this.readUInt16(!0) + (this.readUInt8() << 16) : (this.readUInt16() << 8) + this.readUInt8();
};
he.prototype.peekUInt24 = function(r, e) {
  return r == null && (r = 0), e ? this.peekUInt16(r, !0) + (this.peekUInt8(r + 2) << 16) : (this.peekUInt16(r) << 8) + this.peekUInt8(r + 2);
};
he.prototype.readInt24 = function(r) {
  return r ? this.readUInt16(!0) + (this.readInt8() << 16) : (this.readInt16() << 8) + this.readUInt8();
};
he.prototype.peekInt24 = function(r, e) {
  return r == null && (r = 0), e ? this.peekUInt16(r, !0) + (this.peekInt8(r + 2) << 16) : (this.peekInt16(r) << 8) + this.peekUInt8(r + 2);
};
he.prototype.readUInt32 = function(r) {
  return this.read(4, r), Vs[0];
};
he.prototype.peekUInt32 = function(r, e) {
  return r == null && (r = 0), this.peek(4, r, e), Vs[0];
};
he.prototype.readInt32 = function(r) {
  return this.read(4, r), wd[0];
};
he.prototype.peekInt32 = function(r, e) {
  return r == null && (r = 0), this.peek(4, r, e), wd[0];
};
he.prototype.readFloat32 = function(r) {
  return this.read(4, r), Ld[0];
};
he.prototype.peekFloat32 = function(r, e) {
  return r == null && (r = 0), this.peek(4, r, e), Ld[0];
};
he.prototype.readFloat64 = function(r) {
  return this.read(8, r), xn ? xn[0] : Dd();
};
Dd = function() {
  let r, e, t, i, s, n;
  return i = Vs[0], t = Vs[1], !t || t === 2147483648 ? 0 : (n = 1 - (t >>> 31) * 2, r = t >>> 20 & 2047, e = t & 1048575, r === 2047 ? e ? NaN : n * (1 / 0) : (r -= 1023, s = (e | 1048576) * Math.pow(2, r - 20), s += i * Math.pow(2, r - 52), n * s));
};
he.prototype.peekFloat64 = function(r, e) {
  return r == null && (r = 0), this.peek(8, r, e), xn ? xn[0] : Dd();
};
he.prototype.readFloat80 = function(r) {
  return this.read(10, r), Pd();
};
Pd = function() {
  let r, e, t, i, s, n, a;
  return i = Vs[0], s = Vs[1], r = Ws[9], e = Ws[8], a = 1 - (r >>> 7) * 2, t = (r & 127) << 8 | e, t === 0 && s === 0 && i === 0 ? 0 : t === 32767 ? s === 0 && i === 0 ? a * (1 / 0) : NaN : (t -= 16383, n = s * Math.pow(2, t - 31), n += i * Math.pow(2, t - 63), a * n);
};
he.prototype.peekFloat80 = function(r, e) {
  return r == null && (r = 0), this.peek(10, r, e), Pd();
};
he.prototype.readBuffer = function(r) {
  let e, t, i, s, n;
  for (s = at.allocate(r), n = s.data, e = t = 0, i = r; t < i; e = t += 1)
    n[e] = this.readUInt8();
  return s;
};
he.prototype.peekBuffer = function(r, e) {
  let t, i, s, n, a;
  for (r == null && (r = 0), n = at.allocate(e), a = n.data, t = i = 0, s = e; i < s; t = i += 1)
    a[t] = this.peekUInt8(r + t);
  return n;
};
he.prototype.readSingleBuffer = function(r) {
  let e;
  return e = this.list.first.slice(this.localOffset, r), this.advance(e.length), e;
};
he.prototype.peekSingleBuffer = function(r, e) {
  let t;
  return t = this.list.first.slice(this.localOffset + r, e), t;
};
he.prototype.readString = function(r, e) {
  return e == null && (e = "ascii"), Id.call(this, 0, r, e, !0);
};
he.prototype.peekString = function(r, e, t) {
  return r == null && (r = 0), t == null && (t = "ascii"), Id.call(this, r, e, t, !1);
};
Id = function(r, e, t, i) {
  let s, n, a, o, c, l, d, h, u, f, p, m, g;
  switch (t = t.toLowerCase(), u = e === null ? 0 : -1, e == null && (e = 1 / 0), d = r + e, p = "", t) {
    case "ascii":
    case "latin1":
      for (; r < d && (l = this.peekUInt8(r++)) !== u; )
        p += String.fromCharCode(l);
      break;
    case "utf8":
    case "utf-8":
      for (; r < d && (s = this.peekUInt8(r++)) !== u; )
        s & 128 ? (s & 224) === 192 ? (n = this.peekUInt8(r++) & 63, p += String.fromCharCode((s & 31) << 6 | n)) : (s & 240) === 224 ? (n = this.peekUInt8(r++) & 63, a = this.peekUInt8(r++) & 63, p += String.fromCharCode((s & 15) << 12 | n << 6 | a)) : (s & 248) === 240 && (n = this.peekUInt8(r++) & 63, a = this.peekUInt8(r++) & 63, o = this.peekUInt8(r++) & 63, f = ((s & 15) << 18 | n << 12 | a << 6 | o) - 65536, p += String.fromCharCode(55296 + (f >> 10), 56320 + (f & 1023))) : p += String.fromCharCode(s);
      break;
    case "utf16-be":
    case "utf16be":
    case "utf16le":
    case "utf16-le":
    case "utf16bom":
    case "utf16-bom":
      switch (t) {
        case "utf16be":
        case "utf16-be":
          h = !1;
          break;
        case "utf16le":
        case "utf16-le":
          h = !0;
          break;
        case "utf16bom":
        case "utf16-bom":
          if (e < 2 || (c = this.peekUInt16(r)) === u)
            return i && this.advance(r += 2), p;
          h = c === 65534, r += 2;
      }
      for (; r < d && (m = this.peekUInt16(r, h)) !== u; )
        if (r += 2, m < 55296 || m > 57343)
          p += String.fromCharCode(m);
        else {
          if (m > 56319)
            throw new Error("Invalid utf16 sequence.");
          if (g = this.peekUInt16(r, h), g < 56320 || g > 57343)
            throw new Error("Invalid utf16 sequence.");
          p += String.fromCharCode(m, g), r += 2;
        }
      m === u && (r += 2);
      break;
    default:
      throw new Error("Unknown encoding: " + t);
  }
  return i && this.advance(r), p;
};
function Ct(r) {
  this.stream = r, this.bitPosition = 0;
}
Ct.prototype.copy = function() {
  let r;
  return r = new Ct(this.stream.copy()), r.bitPosition = this.bitPosition, r;
};
Ct.prototype.offset = function() {
  return 8 * this.stream.offset + this.bitPosition;
};
Ct.prototype.available = function(r) {
  return this.stream.available((r + 8 - this.bitPosition) / 8);
};
Ct.prototype.advance = function(r) {
  let e;
  return e = this.bitPosition + r, this.stream.advance(e >> 3), this.bitPosition = e & 7;
};
Ct.prototype.rewind = function(r) {
  let e;
  return e = this.bitPosition - r, this.stream.rewind(Math.abs(e >> 3)), this.bitPosition = e & 7;
};
Ct.prototype.seek = function(r) {
  let e;
  if (e = this.offset(), r > e)
    return this.advance(r - e);
  if (r < e)
    return this.rewind(e - r);
};
Ct.prototype.align = function() {
  if (this.bitPosition !== 0)
    return this.bitPosition = 0, this.stream.advance(1);
};
Ct.prototype.read = function(r, e) {
  let t, i, s, n, a, o, c;
  if (r === 0)
    return 0;
  if (c = r + this.bitPosition, c <= 8)
    t = (this.stream.peekUInt8() << this.bitPosition & 255) >>> 8 - r;
  else if (c <= 16)
    t = (this.stream.peekUInt16() << this.bitPosition & 65535) >>> 16 - r;
  else if (c <= 24)
    t = (this.stream.peekUInt24() << this.bitPosition & 16777215) >>> 24 - r;
  else if (c <= 32)
    t = this.stream.peekUInt32() << this.bitPosition >>> 32 - r;
  else if (c <= 40)
    i = this.stream.peekUInt8(0) * 4294967296, s = this.stream.peekUInt8(1) << 24 >>> 0, n = this.stream.peekUInt8(2) << 16, a = this.stream.peekUInt8(3) << 8, o = this.stream.peekUInt8(4), t = i + s + n + a + o, t %= Math.pow(2, 40 - this.bitPosition), t = Math.floor(t / Math.pow(2, 40 - this.bitPosition - r));
  else
    throw new Error("Too many bits!");
  return e && (c < 32 ? t >>> r - 1 && (t = ((1 << r >>> 0) - t) * -1) : t / Math.pow(2, r - 1) | 0 && (t = (Math.pow(2, r) - t) * -1)), this.advance(r), t;
};
Ct.prototype.peek = function(r, e) {
  let t, i, s, n, a, o, c;
  if (r === 0)
    return 0;
  if (c = r + this.bitPosition, c <= 8)
    t = (this.stream.peekUInt8() << this.bitPosition & 255) >>> 8 - r;
  else if (c <= 16)
    t = (this.stream.peekUInt16() << this.bitPosition & 65535) >>> 16 - r;
  else if (c <= 24)
    t = (this.stream.peekUInt24() << this.bitPosition & 16777215) >>> 24 - r;
  else if (c <= 32)
    t = this.stream.peekUInt32() << this.bitPosition >>> 32 - r;
  else if (c <= 40)
    i = this.stream.peekUInt8(0) * 4294967296, s = this.stream.peekUInt8(1) << 24 >>> 0, n = this.stream.peekUInt8(2) << 16, a = this.stream.peekUInt8(3) << 8, o = this.stream.peekUInt8(4), t = i + s + n + a + o, t %= Math.pow(2, 40 - this.bitPosition), t = Math.floor(t / Math.pow(2, 40 - this.bitPosition - r));
  else
    throw new Error("Too many bits!");
  return e && (c < 32 ? t >>> r - 1 && (t = ((1 << r >>> 0) - t) * -1) : t / Math.pow(2, r - 1) | 0 && (t = (Math.pow(2, r) - t) * -1)), t;
};
Ct.prototype.readLSB = function(r, e) {
  let t, i;
  if (r === 0)
    return 0;
  if (r > 40)
    throw new Error("Too many bits!");
  return i = r + this.bitPosition, t = this.stream.peekUInt8(0) >>> this.bitPosition, i > 8 && (t |= this.stream.peekUInt8(1) << 8 - this.bitPosition), i > 16 && (t |= this.stream.peekUInt8(2) << 16 - this.bitPosition), i > 24 && (t += this.stream.peekUInt8(3) << 24 - this.bitPosition >>> 0), i > 32 && (t += this.stream.peekUInt8(4) * Math.pow(2, 32 - this.bitPosition)), i >= 32 ? t %= Math.pow(2, r) : t &= (1 << r) - 1, e && (i < 32 ? t >>> r - 1 && (t = ((1 << r >>> 0) - t) * -1) : t / Math.pow(2, r - 1) | 0 && (t = (Math.pow(2, r) - t) * -1)), this.advance(r), t;
};
Ct.prototype.peekLSB = function(r, e) {
  let t, i;
  if (r === 0)
    return 0;
  if (r > 40)
    throw new Error("Too many bits!");
  return i = r + this.bitPosition, t = this.stream.peekUInt8(0) >>> this.bitPosition, i > 8 && (t |= this.stream.peekUInt8(1) << 8 - this.bitPosition), i > 16 && (t |= this.stream.peekUInt8(2) << 16 - this.bitPosition), i > 24 && (t += this.stream.peekUInt8(3) << 24 - this.bitPosition >>> 0), i > 32 && (t += this.stream.peekUInt8(4) * Math.pow(2, 32 - this.bitPosition)), i >= 32 ? t %= Math.pow(2, r) : t &= (1 << r) - 1, e && (i < 32 ? t >>> r - 1 && (t = ((1 << r >>> 0) - t) * -1) : t / Math.pow(2, r - 1) | 0 && (t = (Math.pow(2, r) - t) * -1)), t;
};
class Co extends ve {
  constructor(e, t) {
    super();
    let i, s;
    i = new Ji(), i.append(t), this.stream = new he(i), s = !1, e.on("data", (n) => {
      let a;
      s = !0, i.append(n);
      try {
        return this.readChunk(n);
      } catch (o) {
        return a = o, this.emit("error", a);
      }
    }), e.on("error", (n) => this.emit("error", n)), e.on("end", () => (s || this.readChunk(t), this.emit("end"))), this.init();
  }
  probe() {
    let e = this.stream, t = e.offset;
    for (; e.available(2); )
      if ((e.readUInt16() & 65526) === 65520)
        return e.seek(t), !0;
    return e.seek(t), !1;
  }
  init() {
    this.bitstream = new Ct(this.stream);
  }
  // Reads an ADTS header
  // See http://wiki.multimedia.cx/index.php?title=ADTS
  static readHeader(e) {
    if (e.read(12) !== 4095)
      throw new Error("Invalid ADTS header.");
    let t = {};
    e.advance(3);
    let i = !!e.read(1);
    return t.profile = e.read(2) + 1, t.samplingIndex = e.read(4), e.advance(1), t.chanConfig = e.read(3), e.advance(4), t.frameLength = e.read(13), e.advance(11), t.numFrames = e.read(2) + 1, i || e.advance(16), t;
  }
  readChunk() {
    if (!this.sentHeader) {
      let e = this.stream.offset, t = Co.readHeader(this.bitstream);
      this.emit("format", {
        formatID: "aac ",
        sampleRate: Ra[t.samplingIndex],
        channelsPerFrame: t.chanConfig,
        bitsPerChannel: 16
      });
      let i = new Uint8Array(2);
      i[0] = t.profile << 3 | t.samplingIndex >> 1 & 7, i[1] = (t.samplingIndex & 1) << 7 | t.chanConfig << 3, this.emit("cookie", new at(i)), this.stream.seek(e), this.sentHeader = !0;
    }
    for (; this.stream.available(1); ) {
      let e = this.stream.readSingleBuffer(this.stream.remainingBytes());
      this.emit("data", e);
    }
  }
}
const _3 = [
  [1, 0, 0, 0, 0, 0],
  [5, 16, 1, 0, 0, 0],
  [5, 17, -1, 0, 0, 0],
  [5, 18, 0, 0, 0, -1],
  [5, 19, 0, 1, 0, 0],
  [5, 20, 0, 0, 0, 1],
  [5, 21, 0, 0, -1, 0],
  [5, 22, 0, 0, 1, 0],
  [5, 23, 0, -1, 0, 0],
  [7, 96, 1, -1, 0, 0],
  [7, 97, -1, 1, 0, 0],
  [7, 98, 0, 0, -1, 1],
  [7, 99, 0, 1, -1, 0],
  [7, 100, 0, -1, 1, 0],
  [7, 101, 0, 0, 1, -1],
  [7, 102, 1, 1, 0, 0],
  [7, 103, 0, 0, -1, -1],
  [7, 104, -1, -1, 0, 0],
  [7, 105, 0, -1, -1, 0],
  [7, 106, 1, 0, -1, 0],
  [7, 107, 0, 1, 0, -1],
  [7, 108, -1, 0, 1, 0],
  [7, 109, 0, 0, 1, 1],
  [7, 110, 1, 0, 1, 0],
  [7, 111, 0, -1, 0, 1],
  [7, 112, 0, 1, 1, 0],
  [7, 113, 0, 1, 0, 1],
  [7, 114, -1, 0, -1, 0],
  [7, 115, 1, 0, 0, 1],
  [7, 116, -1, 0, 0, -1],
  [7, 117, 1, 0, 0, -1],
  [7, 118, -1, 0, 0, 1],
  [7, 119, 0, -1, 0, -1],
  [9, 480, 1, 1, -1, 0],
  [9, 481, -1, 1, -1, 0],
  [9, 482, 1, -1, 1, 0],
  [9, 483, 0, 1, 1, -1],
  [9, 484, 0, 1, -1, 1],
  [9, 485, 0, -1, 1, 1],
  [9, 486, 0, -1, 1, -1],
  [9, 487, 1, -1, -1, 0],
  [9, 488, 1, 0, -1, 1],
  [9, 489, 0, 1, -1, -1],
  [9, 490, -1, 1, 1, 0],
  [9, 491, -1, 0, 1, -1],
  [9, 492, -1, -1, 1, 0],
  [9, 493, 0, -1, -1, 1],
  [9, 494, 1, -1, 0, 1],
  [9, 495, 1, -1, 0, -1],
  [9, 496, -1, 1, 0, -1],
  [9, 497, -1, -1, -1, 0],
  [9, 498, 0, -1, -1, -1],
  [9, 499, 0, 1, 1, 1],
  [9, 500, 1, 0, 1, -1],
  [9, 501, 1, 1, 0, 1],
  [9, 502, -1, 1, 0, 1],
  [9, 503, 1, 1, 1, 0],
  [10, 1008, -1, -1, 0, 1],
  [10, 1009, -1, 0, -1, -1],
  [10, 1010, 1, 1, 0, -1],
  [10, 1011, 1, 0, -1, -1],
  [10, 1012, -1, 0, -1, 1],
  [10, 1013, -1, -1, 0, -1],
  [10, 1014, -1, 0, 1, 1],
  [10, 1015, 1, 0, 1, 1],
  [11, 2032, 1, -1, 1, -1],
  [11, 2033, -1, 1, -1, 1],
  [11, 2034, -1, 1, 1, -1],
  [11, 2035, 1, -1, -1, 1],
  [11, 2036, 1, 1, 1, 1],
  [11, 2037, -1, -1, 1, 1],
  [11, 2038, 1, 1, -1, -1],
  [11, 2039, -1, -1, 1, -1],
  [11, 2040, -1, -1, -1, -1],
  [11, 2041, 1, 1, -1, 1],
  [11, 2042, 1, -1, 1, 1],
  [11, 2043, -1, 1, 1, 1],
  [11, 2044, -1, 1, -1, -1],
  [11, 2045, -1, -1, -1, 1],
  [11, 2046, 1, -1, -1, -1],
  [11, 2047, 1, 1, 1, -1]
], y3 = [
  [3, 0, 0, 0, 0, 0],
  [4, 2, 1, 0, 0, 0],
  [5, 6, -1, 0, 0, 0],
  [5, 7, 0, 0, 0, 1],
  [5, 8, 0, 0, -1, 0],
  [5, 9, 0, 0, 0, -1],
  [5, 10, 0, -1, 0, 0],
  [5, 11, 0, 0, 1, 0],
  [5, 12, 0, 1, 0, 0],
  [6, 26, 0, -1, 1, 0],
  [6, 27, -1, 1, 0, 0],
  [6, 28, 0, 1, -1, 0],
  [6, 29, 0, 0, 1, -1],
  [6, 30, 0, 1, 0, -1],
  [6, 31, 0, 0, -1, 1],
  [6, 32, -1, 0, 0, -1],
  [6, 33, 1, -1, 0, 0],
  [6, 34, 1, 0, -1, 0],
  [6, 35, -1, -1, 0, 0],
  [6, 36, 0, 0, -1, -1],
  [6, 37, 1, 0, 1, 0],
  [6, 38, 1, 0, 0, 1],
  [6, 39, 0, -1, 0, 1],
  [6, 40, -1, 0, 1, 0],
  [6, 41, 0, 1, 0, 1],
  [6, 42, 0, -1, -1, 0],
  [6, 43, -1, 0, 0, 1],
  [6, 44, 0, -1, 0, -1],
  [6, 45, -1, 0, -1, 0],
  [6, 46, 1, 1, 0, 0],
  [6, 47, 0, 1, 1, 0],
  [6, 48, 0, 0, 1, 1],
  [6, 49, 1, 0, 0, -1],
  [7, 100, 0, 1, -1, 1],
  [7, 101, 1, 0, -1, 1],
  [7, 102, -1, 1, -1, 0],
  [7, 103, 0, -1, 1, -1],
  [7, 104, 1, -1, 1, 0],
  [7, 105, 1, 1, 0, -1],
  [7, 106, 1, 0, 1, 1],
  [7, 107, -1, 1, 1, 0],
  [7, 108, 0, -1, -1, 1],
  [7, 109, 1, 1, 1, 0],
  [7, 110, -1, 0, 1, -1],
  [7, 111, -1, -1, -1, 0],
  [7, 112, -1, 0, -1, 1],
  [7, 113, 1, -1, -1, 0],
  [7, 114, 1, 1, -1, 0],
  [8, 230, 1, -1, 0, 1],
  [8, 231, -1, 1, 0, -1],
  [8, 232, -1, -1, 1, 0],
  [8, 233, -1, 0, 1, 1],
  [8, 234, -1, -1, 0, 1],
  [8, 235, -1, -1, 0, -1],
  [8, 236, 0, -1, -1, -1],
  [8, 237, 1, 0, 1, -1],
  [8, 238, 1, 0, -1, -1],
  [8, 239, 0, 1, -1, -1],
  [8, 240, 0, 1, 1, 1],
  [8, 241, -1, 1, 0, 1],
  [8, 242, -1, 0, -1, -1],
  [8, 243, 0, 1, 1, -1],
  [8, 244, 1, -1, 0, -1],
  [8, 245, 0, -1, 1, 1],
  [8, 246, 1, 1, 0, 1],
  [8, 247, 1, -1, 1, -1],
  [8, 248, -1, 1, -1, 1],
  [9, 498, 1, -1, -1, 1],
  [9, 499, -1, -1, -1, -1],
  [9, 500, -1, 1, 1, -1],
  [9, 501, -1, 1, 1, 1],
  [9, 502, 1, 1, 1, 1],
  [9, 503, -1, -1, 1, -1],
  [9, 504, 1, -1, 1, 1],
  [9, 505, -1, 1, -1, -1],
  [9, 506, -1, -1, 1, 1],
  [9, 507, 1, 1, -1, -1],
  [9, 508, 1, -1, -1, -1],
  [9, 509, -1, -1, -1, 1],
  [9, 510, 1, 1, -1, 1],
  [9, 511, 1, 1, 1, -1]
], x3 = [
  [1, 0, 0, 0, 0, 0],
  [4, 8, 1, 0, 0, 0],
  [4, 9, 0, 0, 0, 1],
  [4, 10, 0, 1, 0, 0],
  [4, 11, 0, 0, 1, 0],
  [5, 24, 1, 1, 0, 0],
  [5, 25, 0, 0, 1, 1],
  [6, 52, 0, 1, 1, 0],
  [6, 53, 0, 1, 0, 1],
  [6, 54, 1, 0, 1, 0],
  [6, 55, 0, 1, 1, 1],
  [6, 56, 1, 0, 0, 1],
  [6, 57, 1, 1, 1, 0],
  [7, 116, 1, 1, 1, 1],
  [7, 117, 1, 0, 1, 1],
  [7, 118, 1, 1, 0, 1],
  [8, 238, 2, 0, 0, 0],
  [8, 239, 0, 0, 0, 2],
  [8, 240, 0, 0, 1, 2],
  [8, 241, 2, 1, 0, 0],
  [8, 242, 1, 2, 1, 0],
  [9, 486, 0, 0, 2, 1],
  [9, 487, 0, 1, 2, 1],
  [9, 488, 1, 2, 0, 0],
  [9, 489, 0, 1, 1, 2],
  [9, 490, 2, 1, 1, 0],
  [9, 491, 0, 0, 2, 0],
  [9, 492, 0, 2, 1, 0],
  [9, 493, 0, 1, 2, 0],
  [9, 494, 0, 2, 0, 0],
  [9, 495, 0, 1, 0, 2],
  [9, 496, 2, 0, 1, 0],
  [9, 497, 1, 2, 1, 1],
  [9, 498, 0, 2, 1, 1],
  [9, 499, 1, 1, 2, 0],
  [9, 500, 1, 1, 2, 1],
  [10, 1002, 1, 2, 0, 1],
  [10, 1003, 1, 0, 2, 0],
  [10, 1004, 1, 0, 2, 1],
  [10, 1005, 0, 2, 0, 1],
  [10, 1006, 2, 1, 1, 1],
  [10, 1007, 1, 1, 1, 2],
  [10, 1008, 2, 1, 0, 1],
  [10, 1009, 1, 0, 1, 2],
  [10, 1010, 0, 0, 2, 2],
  [10, 1011, 0, 1, 2, 2],
  [10, 1012, 2, 2, 1, 0],
  [10, 1013, 1, 2, 2, 0],
  [10, 1014, 1, 0, 0, 2],
  [10, 1015, 2, 0, 0, 1],
  [10, 1016, 0, 2, 2, 1],
  [11, 2034, 2, 2, 0, 0],
  [11, 2035, 1, 2, 2, 1],
  [11, 2036, 1, 1, 0, 2],
  [11, 2037, 2, 0, 1, 1],
  [11, 2038, 1, 1, 2, 2],
  [11, 2039, 2, 2, 1, 1],
  [11, 2040, 0, 2, 2, 0],
  [11, 2041, 0, 2, 1, 2],
  [12, 4084, 1, 0, 2, 2],
  [12, 4085, 2, 2, 0, 1],
  [12, 4086, 2, 1, 2, 0],
  [12, 4087, 2, 2, 2, 0],
  [12, 4088, 0, 2, 2, 2],
  [12, 4089, 2, 2, 2, 1],
  [12, 4090, 2, 1, 2, 1],
  [12, 4091, 1, 2, 1, 2],
  [12, 4092, 1, 2, 2, 2],
  [13, 8186, 0, 2, 0, 2],
  [13, 8187, 2, 0, 2, 0],
  [13, 8188, 1, 2, 0, 2],
  [14, 16378, 2, 0, 2, 1],
  [14, 16379, 2, 1, 1, 2],
  [14, 16380, 2, 1, 0, 2],
  [15, 32762, 2, 2, 2, 2],
  [15, 32763, 2, 2, 1, 2],
  [15, 32764, 2, 1, 2, 2],
  [15, 32765, 2, 0, 1, 2],
  [15, 32766, 2, 0, 0, 2],
  [16, 65534, 2, 2, 0, 2],
  [16, 65535, 2, 0, 2, 2]
], v3 = [
  [4, 0, 1, 1, 1, 1],
  [4, 1, 0, 1, 1, 1],
  [4, 2, 1, 1, 0, 1],
  [4, 3, 1, 1, 1, 0],
  [4, 4, 1, 0, 1, 1],
  [4, 5, 1, 0, 0, 0],
  [4, 6, 1, 1, 0, 0],
  [4, 7, 0, 0, 0, 0],
  [4, 8, 0, 0, 1, 1],
  [4, 9, 1, 0, 1, 0],
  [5, 20, 1, 0, 0, 1],
  [5, 21, 0, 1, 1, 0],
  [5, 22, 0, 0, 0, 1],
  [5, 23, 0, 1, 0, 1],
  [5, 24, 0, 0, 1, 0],
  [5, 25, 0, 1, 0, 0],
  [7, 104, 2, 1, 1, 1],
  [7, 105, 1, 1, 2, 1],
  [7, 106, 1, 2, 1, 1],
  [7, 107, 1, 1, 1, 2],
  [7, 108, 2, 1, 1, 0],
  [7, 109, 2, 1, 0, 1],
  [7, 110, 1, 2, 1, 0],
  [7, 111, 2, 0, 1, 1],
  [7, 112, 0, 1, 2, 1],
  [8, 226, 0, 1, 1, 2],
  [8, 227, 1, 1, 2, 0],
  [8, 228, 0, 2, 1, 1],
  [8, 229, 1, 0, 1, 2],
  [8, 230, 1, 2, 0, 1],
  [8, 231, 1, 1, 0, 2],
  [8, 232, 1, 0, 2, 1],
  [8, 233, 2, 1, 0, 0],
  [8, 234, 2, 0, 1, 0],
  [8, 235, 1, 2, 0, 0],
  [8, 236, 2, 0, 0, 1],
  [8, 237, 0, 1, 0, 2],
  [8, 238, 0, 2, 1, 0],
  [8, 239, 0, 0, 1, 2],
  [8, 240, 0, 1, 2, 0],
  [8, 241, 0, 2, 0, 1],
  [8, 242, 1, 0, 0, 2],
  [8, 243, 0, 0, 2, 1],
  [8, 244, 1, 0, 2, 0],
  [8, 245, 2, 0, 0, 0],
  [8, 246, 0, 0, 0, 2],
  [9, 494, 0, 2, 0, 0],
  [9, 495, 0, 0, 2, 0],
  [9, 496, 1, 2, 2, 1],
  [9, 497, 2, 2, 1, 1],
  [9, 498, 2, 1, 2, 1],
  [9, 499, 1, 1, 2, 2],
  [9, 500, 1, 2, 1, 2],
  [9, 501, 2, 1, 1, 2],
  [10, 1004, 1, 2, 2, 0],
  [10, 1005, 2, 2, 1, 0],
  [10, 1006, 2, 1, 2, 0],
  [10, 1007, 0, 2, 2, 1],
  [10, 1008, 0, 1, 2, 2],
  [10, 1009, 2, 2, 0, 1],
  [10, 1010, 0, 2, 1, 2],
  [10, 1011, 2, 0, 2, 1],
  [10, 1012, 1, 0, 2, 2],
  [10, 1013, 2, 2, 2, 1],
  [10, 1014, 1, 2, 0, 2],
  [10, 1015, 2, 0, 1, 2],
  [10, 1016, 2, 1, 0, 2],
  [10, 1017, 1, 2, 2, 2],
  [11, 2036, 2, 1, 2, 2],
  [11, 2037, 2, 2, 1, 2],
  [11, 2038, 0, 2, 2, 0],
  [11, 2039, 2, 2, 0, 0],
  [11, 2040, 0, 0, 2, 2],
  [11, 2041, 2, 0, 2, 0],
  [11, 2042, 0, 2, 0, 2],
  [11, 2043, 2, 0, 0, 2],
  [11, 2044, 2, 2, 2, 2],
  [11, 2045, 0, 2, 2, 2],
  [11, 2046, 2, 2, 2, 0],
  [12, 4094, 2, 2, 0, 2],
  [12, 4095, 2, 0, 2, 2]
], E3 = [
  [1, 0, 0, 0],
  [4, 8, -1, 0],
  [4, 9, 1, 0],
  [4, 10, 0, 1],
  [4, 11, 0, -1],
  [5, 24, 1, -1],
  [5, 25, -1, 1],
  [5, 26, -1, -1],
  [5, 27, 1, 1],
  [7, 112, -2, 0],
  [7, 113, 0, 2],
  [7, 114, 2, 0],
  [7, 115, 0, -2],
  [8, 232, -2, -1],
  [8, 233, 2, 1],
  [8, 234, -1, -2],
  [8, 235, 1, 2],
  [8, 236, -2, 1],
  [8, 237, 2, -1],
  [8, 238, -1, 2],
  [8, 239, 1, -2],
  [8, 240, -3, 0],
  [8, 241, 3, 0],
  [8, 242, 0, -3],
  [8, 243, 0, 3],
  [9, 488, -3, -1],
  [9, 489, 1, 3],
  [9, 490, 3, 1],
  [9, 491, -1, -3],
  [9, 492, -3, 1],
  [9, 493, 3, -1],
  [9, 494, 1, -3],
  [9, 495, -1, 3],
  [9, 496, -2, 2],
  [9, 497, 2, 2],
  [9, 498, -2, -2],
  [9, 499, 2, -2],
  [10, 1e3, -3, -2],
  [10, 1001, 3, -2],
  [10, 1002, -2, 3],
  [10, 1003, 2, -3],
  [10, 1004, 3, 2],
  [10, 1005, 2, 3],
  [10, 1006, -3, 2],
  [10, 1007, -2, -3],
  [10, 1008, 0, -4],
  [10, 1009, -4, 0],
  [10, 1010, 4, 1],
  [10, 1011, 4, 0],
  [11, 2024, -4, -1],
  [11, 2025, 0, 4],
  [11, 2026, 4, -1],
  [11, 2027, -1, -4],
  [11, 2028, 1, 4],
  [11, 2029, -1, 4],
  [11, 2030, -4, 1],
  [11, 2031, 1, -4],
  [11, 2032, 3, -3],
  [11, 2033, -3, -3],
  [11, 2034, -3, 3],
  [11, 2035, -2, 4],
  [11, 2036, -4, -2],
  [11, 2037, 4, 2],
  [11, 2038, 2, -4],
  [11, 2039, 2, 4],
  [11, 2040, 3, 3],
  [11, 2041, -4, 2],
  [12, 4084, -2, -4],
  [12, 4085, 4, -2],
  [12, 4086, 3, -4],
  [12, 4087, -4, -3],
  [12, 4088, -4, 3],
  [12, 4089, 3, 4],
  [12, 4090, -3, 4],
  [12, 4091, 4, 3],
  [12, 4092, 4, -3],
  [12, 4093, -3, -4],
  [13, 8188, 4, -4],
  [13, 8189, -4, 4],
  [13, 8190, 4, 4],
  [13, 8191, -4, -4]
], S3 = [
  [4, 0, 0, 0],
  [4, 1, 1, 0],
  [4, 2, 0, -1],
  [4, 3, 0, 1],
  [4, 4, -1, 0],
  [4, 5, 1, 1],
  [4, 6, -1, 1],
  [4, 7, 1, -1],
  [4, 8, -1, -1],
  [6, 36, 2, -1],
  [6, 37, 2, 1],
  [6, 38, -2, 1],
  [6, 39, -2, -1],
  [6, 40, -2, 0],
  [6, 41, -1, 2],
  [6, 42, 2, 0],
  [6, 43, 1, -2],
  [6, 44, 1, 2],
  [6, 45, 0, -2],
  [6, 46, -1, -2],
  [6, 47, 0, 2],
  [6, 48, 2, -2],
  [6, 49, -2, 2],
  [6, 50, -2, -2],
  [6, 51, 2, 2],
  [7, 104, -3, 1],
  [7, 105, 3, 1],
  [7, 106, 3, -1],
  [7, 107, -1, 3],
  [7, 108, -3, -1],
  [7, 109, 1, 3],
  [7, 110, 1, -3],
  [7, 111, -1, -3],
  [7, 112, 3, 0],
  [7, 113, -3, 0],
  [7, 114, 0, -3],
  [7, 115, 0, 3],
  [7, 116, 3, 2],
  [8, 234, -3, -2],
  [8, 235, -2, 3],
  [8, 236, 2, 3],
  [8, 237, 3, -2],
  [8, 238, 2, -3],
  [8, 239, -2, -3],
  [8, 240, -3, 2],
  [8, 241, 3, 3],
  [9, 484, 3, -3],
  [9, 485, -3, -3],
  [9, 486, -3, 3],
  [9, 487, 1, -4],
  [9, 488, -1, -4],
  [9, 489, 4, 1],
  [9, 490, -4, 1],
  [9, 491, -4, -1],
  [9, 492, 1, 4],
  [9, 493, 4, -1],
  [9, 494, -1, 4],
  [9, 495, 0, -4],
  [9, 496, -4, 2],
  [9, 497, -4, -2],
  [9, 498, 2, 4],
  [9, 499, -2, -4],
  [9, 500, -4, 0],
  [9, 501, 4, 2],
  [9, 502, 4, -2],
  [9, 503, -2, 4],
  [9, 504, 4, 0],
  [9, 505, 2, -4],
  [9, 506, 0, 4],
  [10, 1014, -3, -4],
  [10, 1015, -3, 4],
  [10, 1016, 3, -4],
  [10, 1017, 4, -3],
  [10, 1018, 3, 4],
  [10, 1019, 4, 3],
  [10, 1020, -4, 3],
  [10, 1021, -4, -3],
  [11, 2044, 4, 4],
  [11, 2045, -4, 4],
  [11, 2046, -4, -4],
  [11, 2047, 4, -4]
], T3 = [
  [1, 0, 0, 0],
  [3, 4, 1, 0],
  [3, 5, 0, 1],
  [4, 12, 1, 1],
  [6, 52, 2, 1],
  [6, 53, 1, 2],
  [6, 54, 2, 0],
  [6, 55, 0, 2],
  [7, 112, 3, 1],
  [7, 113, 1, 3],
  [7, 114, 2, 2],
  [7, 115, 3, 0],
  [7, 116, 0, 3],
  [8, 234, 2, 3],
  [8, 235, 3, 2],
  [8, 236, 1, 4],
  [8, 237, 4, 1],
  [8, 238, 1, 5],
  [8, 239, 5, 1],
  [8, 240, 3, 3],
  [8, 241, 2, 4],
  [8, 242, 0, 4],
  [8, 243, 4, 0],
  [9, 488, 4, 2],
  [9, 489, 2, 5],
  [9, 490, 5, 2],
  [9, 491, 0, 5],
  [9, 492, 6, 1],
  [9, 493, 5, 0],
  [9, 494, 1, 6],
  [9, 495, 4, 3],
  [9, 496, 3, 5],
  [9, 497, 3, 4],
  [9, 498, 5, 3],
  [9, 499, 2, 6],
  [9, 500, 6, 2],
  [9, 501, 1, 7],
  [10, 1004, 3, 6],
  [10, 1005, 0, 6],
  [10, 1006, 6, 0],
  [10, 1007, 4, 4],
  [10, 1008, 7, 1],
  [10, 1009, 4, 5],
  [10, 1010, 7, 2],
  [10, 1011, 5, 4],
  [10, 1012, 6, 3],
  [10, 1013, 2, 7],
  [10, 1014, 7, 3],
  [10, 1015, 6, 4],
  [10, 1016, 5, 5],
  [10, 1017, 4, 6],
  [10, 1018, 3, 7],
  [11, 2038, 7, 0],
  [11, 2039, 0, 7],
  [11, 2040, 6, 5],
  [11, 2041, 5, 6],
  [11, 2042, 7, 4],
  [11, 2043, 4, 7],
  [11, 2044, 5, 7],
  [11, 2045, 7, 5],
  [12, 4092, 7, 6],
  [12, 4093, 6, 6],
  [12, 4094, 6, 7],
  [12, 4095, 7, 7]
], b3 = [
  [3, 0, 1, 1],
  [4, 2, 2, 1],
  [4, 3, 1, 0],
  [4, 4, 1, 2],
  [4, 5, 0, 1],
  [4, 6, 2, 2],
  [5, 14, 0, 0],
  [5, 15, 2, 0],
  [5, 16, 0, 2],
  [5, 17, 3, 1],
  [5, 18, 1, 3],
  [5, 19, 3, 2],
  [5, 20, 2, 3],
  [6, 42, 3, 3],
  [6, 43, 4, 1],
  [6, 44, 1, 4],
  [6, 45, 4, 2],
  [6, 46, 2, 4],
  [6, 47, 3, 0],
  [6, 48, 0, 3],
  [6, 49, 4, 3],
  [6, 50, 3, 4],
  [6, 51, 5, 2],
  [7, 104, 5, 1],
  [7, 105, 2, 5],
  [7, 106, 1, 5],
  [7, 107, 5, 3],
  [7, 108, 3, 5],
  [7, 109, 4, 4],
  [7, 110, 5, 4],
  [7, 111, 0, 4],
  [7, 112, 4, 5],
  [7, 113, 4, 0],
  [7, 114, 2, 6],
  [7, 115, 6, 2],
  [7, 116, 6, 1],
  [7, 117, 1, 6],
  [8, 236, 3, 6],
  [8, 237, 6, 3],
  [8, 238, 5, 5],
  [8, 239, 5, 0],
  [8, 240, 6, 4],
  [8, 241, 0, 5],
  [8, 242, 4, 6],
  [8, 243, 7, 1],
  [8, 244, 7, 2],
  [8, 245, 2, 7],
  [8, 246, 6, 5],
  [8, 247, 7, 3],
  [8, 248, 1, 7],
  [8, 249, 5, 6],
  [8, 250, 3, 7],
  [9, 502, 6, 6],
  [9, 503, 7, 4],
  [9, 504, 6, 0],
  [9, 505, 4, 7],
  [9, 506, 0, 6],
  [9, 507, 7, 5],
  [9, 508, 7, 6],
  [9, 509, 6, 7],
  [10, 1020, 5, 7],
  [10, 1021, 7, 0],
  [10, 1022, 0, 7],
  [10, 1023, 7, 7]
], A3 = [
  [1, 0, 0, 0],
  [3, 4, 1, 0],
  [3, 5, 0, 1],
  [4, 12, 1, 1],
  [6, 52, 2, 1],
  [6, 53, 1, 2],
  [6, 54, 2, 0],
  [6, 55, 0, 2],
  [7, 112, 3, 1],
  [7, 113, 2, 2],
  [7, 114, 1, 3],
  [8, 230, 3, 0],
  [8, 231, 0, 3],
  [8, 232, 2, 3],
  [8, 233, 3, 2],
  [8, 234, 1, 4],
  [8, 235, 4, 1],
  [8, 236, 2, 4],
  [8, 237, 1, 5],
  [9, 476, 4, 2],
  [9, 477, 3, 3],
  [9, 478, 0, 4],
  [9, 479, 4, 0],
  [9, 480, 5, 1],
  [9, 481, 2, 5],
  [9, 482, 1, 6],
  [9, 483, 3, 4],
  [9, 484, 5, 2],
  [9, 485, 6, 1],
  [9, 486, 4, 3],
  [10, 974, 0, 5],
  [10, 975, 2, 6],
  [10, 976, 5, 0],
  [10, 977, 1, 7],
  [10, 978, 3, 5],
  [10, 979, 1, 8],
  [10, 980, 8, 1],
  [10, 981, 4, 4],
  [10, 982, 5, 3],
  [10, 983, 6, 2],
  [10, 984, 7, 1],
  [10, 985, 0, 6],
  [10, 986, 8, 2],
  [10, 987, 2, 8],
  [10, 988, 3, 6],
  [10, 989, 2, 7],
  [10, 990, 4, 5],
  [10, 991, 9, 1],
  [10, 992, 1, 9],
  [10, 993, 7, 2],
  [11, 1988, 6, 0],
  [11, 1989, 5, 4],
  [11, 1990, 6, 3],
  [11, 1991, 8, 3],
  [11, 1992, 0, 7],
  [11, 1993, 9, 2],
  [11, 1994, 3, 8],
  [11, 1995, 4, 6],
  [11, 1996, 3, 7],
  [11, 1997, 0, 8],
  [11, 1998, 10, 1],
  [11, 1999, 6, 4],
  [11, 2e3, 2, 9],
  [11, 2001, 5, 5],
  [11, 2002, 8, 0],
  [11, 2003, 7, 0],
  [11, 2004, 7, 3],
  [11, 2005, 10, 2],
  [11, 2006, 9, 3],
  [11, 2007, 8, 4],
  [11, 2008, 1, 10],
  [11, 2009, 7, 4],
  [11, 2010, 6, 5],
  [11, 2011, 5, 6],
  [11, 2012, 4, 8],
  [11, 2013, 4, 7],
  [11, 2014, 3, 9],
  [11, 2015, 11, 1],
  [11, 2016, 5, 8],
  [11, 2017, 9, 0],
  [11, 2018, 8, 5],
  [12, 4038, 10, 3],
  [12, 4039, 2, 10],
  [12, 4040, 0, 9],
  [12, 4041, 11, 2],
  [12, 4042, 9, 4],
  [12, 4043, 6, 6],
  [12, 4044, 12, 1],
  [12, 4045, 4, 9],
  [12, 4046, 8, 6],
  [12, 4047, 1, 11],
  [12, 4048, 9, 5],
  [12, 4049, 10, 4],
  [12, 4050, 5, 7],
  [12, 4051, 7, 5],
  [12, 4052, 2, 11],
  [12, 4053, 1, 12],
  [12, 4054, 12, 2],
  [12, 4055, 11, 3],
  [12, 4056, 3, 10],
  [12, 4057, 5, 9],
  [12, 4058, 6, 7],
  [12, 4059, 8, 7],
  [12, 4060, 11, 4],
  [12, 4061, 0, 10],
  [12, 4062, 7, 6],
  [12, 4063, 12, 3],
  [12, 4064, 10, 0],
  [12, 4065, 10, 5],
  [12, 4066, 4, 10],
  [12, 4067, 6, 8],
  [12, 4068, 2, 12],
  [12, 4069, 9, 6],
  [12, 4070, 9, 7],
  [12, 4071, 4, 11],
  [12, 4072, 11, 0],
  [12, 4073, 6, 9],
  [12, 4074, 3, 11],
  [12, 4075, 5, 10],
  [13, 8152, 8, 8],
  [13, 8153, 7, 8],
  [13, 8154, 12, 5],
  [13, 8155, 3, 12],
  [13, 8156, 11, 5],
  [13, 8157, 7, 7],
  [13, 8158, 12, 4],
  [13, 8159, 11, 6],
  [13, 8160, 10, 6],
  [13, 8161, 4, 12],
  [13, 8162, 7, 9],
  [13, 8163, 5, 11],
  [13, 8164, 0, 11],
  [13, 8165, 12, 6],
  [13, 8166, 6, 10],
  [13, 8167, 12, 0],
  [13, 8168, 10, 7],
  [13, 8169, 5, 12],
  [13, 8170, 7, 10],
  [13, 8171, 9, 8],
  [13, 8172, 0, 12],
  [13, 8173, 11, 7],
  [13, 8174, 8, 9],
  [13, 8175, 9, 9],
  [13, 8176, 10, 8],
  [13, 8177, 7, 11],
  [13, 8178, 12, 7],
  [13, 8179, 6, 11],
  [13, 8180, 8, 11],
  [13, 8181, 11, 8],
  [13, 8182, 7, 12],
  [13, 8183, 6, 12],
  [14, 16368, 8, 10],
  [14, 16369, 10, 9],
  [14, 16370, 8, 12],
  [14, 16371, 9, 10],
  [14, 16372, 9, 11],
  [14, 16373, 9, 12],
  [14, 16374, 10, 11],
  [14, 16375, 12, 9],
  [14, 16376, 10, 10],
  [14, 16377, 11, 9],
  [14, 16378, 12, 8],
  [14, 16379, 11, 10],
  [14, 16380, 12, 10],
  [14, 16381, 12, 11],
  [15, 32764, 10, 12],
  [15, 32765, 11, 11],
  [15, 32766, 11, 12],
  [15, 32767, 12, 12]
], C3 = [
  [4, 0, 1, 1],
  [4, 1, 1, 2],
  [4, 2, 2, 1],
  [5, 6, 2, 2],
  [5, 7, 1, 0],
  [5, 8, 0, 1],
  [5, 9, 1, 3],
  [5, 10, 3, 2],
  [5, 11, 3, 1],
  [5, 12, 2, 3],
  [5, 13, 3, 3],
  [6, 28, 2, 0],
  [6, 29, 0, 2],
  [6, 30, 2, 4],
  [6, 31, 4, 2],
  [6, 32, 1, 4],
  [6, 33, 4, 1],
  [6, 34, 0, 0],
  [6, 35, 4, 3],
  [6, 36, 3, 4],
  [6, 37, 3, 0],
  [6, 38, 0, 3],
  [6, 39, 4, 4],
  [6, 40, 2, 5],
  [6, 41, 5, 2],
  [7, 84, 1, 5],
  [7, 85, 5, 1],
  [7, 86, 5, 3],
  [7, 87, 3, 5],
  [7, 88, 5, 4],
  [7, 89, 4, 5],
  [7, 90, 6, 2],
  [7, 91, 2, 6],
  [7, 92, 6, 3],
  [7, 93, 4, 0],
  [7, 94, 6, 1],
  [7, 95, 0, 4],
  [7, 96, 1, 6],
  [7, 97, 3, 6],
  [7, 98, 5, 5],
  [7, 99, 6, 4],
  [7, 100, 4, 6],
  [8, 202, 6, 5],
  [8, 203, 7, 2],
  [8, 204, 3, 7],
  [8, 205, 2, 7],
  [8, 206, 5, 6],
  [8, 207, 8, 2],
  [8, 208, 7, 3],
  [8, 209, 5, 0],
  [8, 210, 7, 1],
  [8, 211, 0, 5],
  [8, 212, 8, 1],
  [8, 213, 1, 7],
  [8, 214, 8, 3],
  [8, 215, 7, 4],
  [8, 216, 4, 7],
  [8, 217, 2, 8],
  [8, 218, 6, 6],
  [8, 219, 7, 5],
  [8, 220, 1, 8],
  [8, 221, 3, 8],
  [8, 222, 8, 4],
  [8, 223, 4, 8],
  [8, 224, 5, 7],
  [8, 225, 8, 5],
  [8, 226, 5, 8],
  [9, 454, 7, 6],
  [9, 455, 6, 7],
  [9, 456, 9, 2],
  [9, 457, 6, 0],
  [9, 458, 6, 8],
  [9, 459, 9, 3],
  [9, 460, 3, 9],
  [9, 461, 9, 1],
  [9, 462, 2, 9],
  [9, 463, 0, 6],
  [9, 464, 8, 6],
  [9, 465, 9, 4],
  [9, 466, 4, 9],
  [9, 467, 10, 2],
  [9, 468, 1, 9],
  [9, 469, 7, 7],
  [9, 470, 8, 7],
  [9, 471, 9, 5],
  [9, 472, 7, 8],
  [9, 473, 10, 3],
  [9, 474, 5, 9],
  [9, 475, 10, 4],
  [9, 476, 2, 10],
  [9, 477, 10, 1],
  [9, 478, 3, 10],
  [9, 479, 9, 6],
  [9, 480, 6, 9],
  [9, 481, 8, 0],
  [9, 482, 4, 10],
  [9, 483, 7, 0],
  [9, 484, 11, 2],
  [10, 970, 7, 9],
  [10, 971, 11, 3],
  [10, 972, 10, 6],
  [10, 973, 1, 10],
  [10, 974, 11, 1],
  [10, 975, 9, 7],
  [10, 976, 0, 7],
  [10, 977, 8, 8],
  [10, 978, 10, 5],
  [10, 979, 3, 11],
  [10, 980, 5, 10],
  [10, 981, 8, 9],
  [10, 982, 11, 5],
  [10, 983, 0, 8],
  [10, 984, 11, 4],
  [10, 985, 2, 11],
  [10, 986, 7, 10],
  [10, 987, 6, 10],
  [10, 988, 10, 7],
  [10, 989, 4, 11],
  [10, 990, 1, 11],
  [10, 991, 12, 2],
  [10, 992, 9, 8],
  [10, 993, 12, 3],
  [10, 994, 11, 6],
  [10, 995, 5, 11],
  [10, 996, 12, 4],
  [10, 997, 11, 7],
  [10, 998, 12, 5],
  [10, 999, 3, 12],
  [10, 1e3, 6, 11],
  [10, 1001, 9, 0],
  [10, 1002, 10, 8],
  [10, 1003, 10, 0],
  [10, 1004, 12, 1],
  [10, 1005, 0, 9],
  [10, 1006, 4, 12],
  [10, 1007, 9, 9],
  [10, 1008, 12, 6],
  [10, 1009, 2, 12],
  [10, 1010, 8, 10],
  [11, 2022, 9, 10],
  [11, 2023, 1, 12],
  [11, 2024, 11, 8],
  [11, 2025, 12, 7],
  [11, 2026, 7, 11],
  [11, 2027, 5, 12],
  [11, 2028, 6, 12],
  [11, 2029, 10, 9],
  [11, 2030, 8, 11],
  [11, 2031, 12, 8],
  [11, 2032, 0, 10],
  [11, 2033, 7, 12],
  [11, 2034, 11, 0],
  [11, 2035, 10, 10],
  [11, 2036, 11, 9],
  [11, 2037, 11, 10],
  [11, 2038, 0, 11],
  [11, 2039, 11, 11],
  [11, 2040, 9, 11],
  [11, 2041, 10, 11],
  [11, 2042, 12, 0],
  [11, 2043, 8, 12],
  [12, 4088, 12, 9],
  [12, 4089, 10, 12],
  [12, 4090, 9, 12],
  [12, 4091, 11, 12],
  [12, 4092, 12, 11],
  [12, 4093, 0, 12],
  [12, 4094, 12, 10],
  [12, 4095, 12, 12]
], R3 = [
  [4, 0, 0, 0],
  [4, 1, 1, 1],
  [5, 4, 16, 16],
  [5, 5, 1, 0],
  [5, 6, 0, 1],
  [5, 7, 2, 1],
  [5, 8, 1, 2],
  [5, 9, 2, 2],
  [6, 20, 1, 3],
  [6, 21, 3, 1],
  [6, 22, 3, 2],
  [6, 23, 2, 0],
  [6, 24, 2, 3],
  [6, 25, 0, 2],
  [6, 26, 3, 3],
  [7, 54, 4, 1],
  [7, 55, 1, 4],
  [7, 56, 4, 2],
  [7, 57, 2, 4],
  [7, 58, 4, 3],
  [7, 59, 3, 4],
  [7, 60, 3, 0],
  [7, 61, 0, 3],
  [7, 62, 5, 1],
  [7, 63, 5, 2],
  [7, 64, 2, 5],
  [7, 65, 4, 4],
  [7, 66, 1, 5],
  [7, 67, 5, 3],
  [7, 68, 3, 5],
  [7, 69, 5, 4],
  [8, 140, 4, 5],
  [8, 141, 6, 2],
  [8, 142, 2, 6],
  [8, 143, 6, 1],
  [8, 144, 6, 3],
  [8, 145, 3, 6],
  [8, 146, 1, 6],
  [8, 147, 4, 16],
  [8, 148, 3, 16],
  [8, 149, 16, 5],
  [8, 150, 16, 3],
  [8, 151, 16, 4],
  [8, 152, 6, 4],
  [8, 153, 16, 6],
  [8, 154, 4, 0],
  [8, 155, 4, 6],
  [8, 156, 0, 4],
  [8, 157, 2, 16],
  [8, 158, 5, 5],
  [8, 159, 5, 16],
  [8, 160, 16, 7],
  [8, 161, 16, 2],
  [8, 162, 16, 8],
  [8, 163, 2, 7],
  [8, 164, 7, 2],
  [8, 165, 3, 7],
  [8, 166, 6, 5],
  [8, 167, 5, 6],
  [8, 168, 6, 16],
  [8, 169, 16, 10],
  [8, 170, 7, 3],
  [8, 171, 7, 1],
  [8, 172, 16, 9],
  [8, 173, 7, 16],
  [8, 174, 1, 16],
  [8, 175, 1, 7],
  [8, 176, 4, 7],
  [8, 177, 16, 11],
  [8, 178, 7, 4],
  [8, 179, 16, 12],
  [8, 180, 8, 16],
  [8, 181, 16, 1],
  [8, 182, 6, 6],
  [8, 183, 9, 16],
  [8, 184, 2, 8],
  [8, 185, 5, 7],
  [8, 186, 10, 16],
  [8, 187, 16, 13],
  [8, 188, 8, 3],
  [8, 189, 8, 2],
  [8, 190, 3, 8],
  [8, 191, 5, 0],
  [8, 192, 16, 14],
  [8, 193, 11, 16],
  [8, 194, 7, 5],
  [8, 195, 4, 8],
  [8, 196, 6, 7],
  [8, 197, 7, 6],
  [8, 198, 0, 5],
  [9, 398, 8, 4],
  [9, 399, 16, 15],
  [9, 400, 12, 16],
  [9, 401, 1, 8],
  [9, 402, 8, 1],
  [9, 403, 14, 16],
  [9, 404, 5, 8],
  [9, 405, 13, 16],
  [9, 406, 3, 9],
  [9, 407, 8, 5],
  [9, 408, 7, 7],
  [9, 409, 2, 9],
  [9, 410, 8, 6],
  [9, 411, 9, 2],
  [9, 412, 9, 3],
  [9, 413, 15, 16],
  [9, 414, 4, 9],
  [9, 415, 6, 8],
  [9, 416, 6, 0],
  [9, 417, 9, 4],
  [9, 418, 5, 9],
  [9, 419, 8, 7],
  [9, 420, 7, 8],
  [9, 421, 1, 9],
  [9, 422, 10, 3],
  [9, 423, 0, 6],
  [9, 424, 10, 2],
  [9, 425, 9, 1],
  [9, 426, 9, 5],
  [9, 427, 4, 10],
  [9, 428, 2, 10],
  [9, 429, 9, 6],
  [9, 430, 3, 10],
  [9, 431, 6, 9],
  [9, 432, 10, 4],
  [9, 433, 8, 8],
  [9, 434, 10, 5],
  [9, 435, 9, 7],
  [9, 436, 11, 3],
  [9, 437, 1, 10],
  [9, 438, 7, 0],
  [9, 439, 10, 6],
  [9, 440, 7, 9],
  [9, 441, 3, 11],
  [9, 442, 5, 10],
  [9, 443, 10, 1],
  [9, 444, 4, 11],
  [9, 445, 11, 2],
  [9, 446, 13, 2],
  [9, 447, 6, 10],
  [9, 448, 13, 3],
  [9, 449, 2, 11],
  [9, 450, 16, 0],
  [9, 451, 5, 11],
  [9, 452, 11, 5],
  [10, 906, 11, 4],
  [10, 907, 9, 8],
  [10, 908, 7, 10],
  [10, 909, 8, 9],
  [10, 910, 0, 16],
  [10, 911, 4, 13],
  [10, 912, 0, 7],
  [10, 913, 3, 13],
  [10, 914, 11, 6],
  [10, 915, 13, 1],
  [10, 916, 13, 4],
  [10, 917, 12, 3],
  [10, 918, 2, 13],
  [10, 919, 13, 5],
  [10, 920, 8, 10],
  [10, 921, 6, 11],
  [10, 922, 10, 8],
  [10, 923, 10, 7],
  [10, 924, 14, 2],
  [10, 925, 12, 4],
  [10, 926, 1, 11],
  [10, 927, 4, 12],
  [10, 928, 11, 1],
  [10, 929, 3, 12],
  [10, 930, 1, 13],
  [10, 931, 12, 2],
  [10, 932, 7, 11],
  [10, 933, 3, 14],
  [10, 934, 5, 12],
  [10, 935, 5, 13],
  [10, 936, 14, 4],
  [10, 937, 4, 14],
  [10, 938, 11, 7],
  [10, 939, 14, 3],
  [10, 940, 12, 5],
  [10, 941, 13, 6],
  [10, 942, 12, 6],
  [10, 943, 8, 0],
  [10, 944, 11, 8],
  [10, 945, 2, 12],
  [10, 946, 9, 9],
  [10, 947, 14, 5],
  [10, 948, 6, 13],
  [10, 949, 10, 10],
  [10, 950, 15, 2],
  [10, 951, 8, 11],
  [10, 952, 9, 10],
  [10, 953, 14, 6],
  [10, 954, 10, 9],
  [10, 955, 5, 14],
  [10, 956, 11, 9],
  [10, 957, 14, 1],
  [10, 958, 2, 14],
  [10, 959, 6, 12],
  [10, 960, 1, 12],
  [10, 961, 13, 8],
  [10, 962, 0, 8],
  [10, 963, 13, 7],
  [10, 964, 7, 12],
  [10, 965, 12, 7],
  [10, 966, 7, 13],
  [10, 967, 15, 3],
  [10, 968, 12, 1],
  [10, 969, 6, 14],
  [10, 970, 2, 15],
  [10, 971, 15, 5],
  [10, 972, 15, 4],
  [10, 973, 1, 14],
  [10, 974, 9, 11],
  [10, 975, 4, 15],
  [10, 976, 14, 7],
  [10, 977, 8, 13],
  [10, 978, 13, 9],
  [10, 979, 8, 12],
  [10, 980, 5, 15],
  [10, 981, 3, 15],
  [10, 982, 10, 11],
  [10, 983, 11, 10],
  [10, 984, 12, 8],
  [10, 985, 15, 6],
  [10, 986, 15, 7],
  [10, 987, 8, 14],
  [10, 988, 15, 1],
  [10, 989, 7, 14],
  [10, 990, 9, 0],
  [10, 991, 0, 9],
  [10, 992, 9, 13],
  [10, 993, 9, 12],
  [10, 994, 12, 9],
  [10, 995, 14, 8],
  [10, 996, 10, 13],
  [10, 997, 14, 9],
  [10, 998, 12, 10],
  [10, 999, 6, 15],
  [10, 1e3, 7, 15],
  [11, 2002, 9, 14],
  [11, 2003, 15, 8],
  [11, 2004, 11, 11],
  [11, 2005, 11, 14],
  [11, 2006, 1, 15],
  [11, 2007, 10, 12],
  [11, 2008, 10, 14],
  [11, 2009, 13, 11],
  [11, 2010, 13, 10],
  [11, 2011, 11, 13],
  [11, 2012, 11, 12],
  [11, 2013, 8, 15],
  [11, 2014, 14, 11],
  [11, 2015, 13, 12],
  [11, 2016, 12, 13],
  [11, 2017, 15, 9],
  [11, 2018, 14, 10],
  [11, 2019, 10, 0],
  [11, 2020, 12, 11],
  [11, 2021, 9, 15],
  [11, 2022, 0, 10],
  [11, 2023, 12, 12],
  [11, 2024, 11, 0],
  [11, 2025, 12, 14],
  [11, 2026, 10, 15],
  [11, 2027, 13, 13],
  [11, 2028, 0, 13],
  [11, 2029, 14, 12],
  [11, 2030, 15, 10],
  [11, 2031, 15, 11],
  [11, 2032, 11, 15],
  [11, 2033, 14, 13],
  [11, 2034, 13, 0],
  [11, 2035, 0, 11],
  [11, 2036, 13, 14],
  [11, 2037, 15, 12],
  [11, 2038, 15, 13],
  [11, 2039, 12, 15],
  [11, 2040, 14, 0],
  [11, 2041, 14, 14],
  [11, 2042, 13, 15],
  [11, 2043, 12, 0],
  [11, 2044, 14, 15],
  [12, 4090, 0, 14],
  [12, 4091, 0, 12],
  [12, 4092, 15, 14],
  [12, 4093, 15, 0],
  [12, 4094, 0, 15],
  [12, 4095, 15, 15]
], Mf = [
  [1, 0, 60],
  [3, 4, 59],
  [4, 10, 61],
  [4, 11, 58],
  [4, 12, 62],
  [5, 26, 57],
  [5, 27, 63],
  [6, 56, 56],
  [6, 57, 64],
  [6, 58, 55],
  [6, 59, 65],
  [7, 120, 66],
  [7, 121, 54],
  [7, 122, 67],
  [8, 246, 53],
  [8, 247, 68],
  [8, 248, 52],
  [8, 249, 69],
  [8, 250, 51],
  [9, 502, 70],
  [9, 503, 50],
  [9, 504, 49],
  [9, 505, 71],
  [10, 1012, 72],
  [10, 1013, 48],
  [10, 1014, 73],
  [10, 1015, 47],
  [10, 1016, 74],
  [10, 1017, 46],
  [11, 2036, 76],
  [11, 2037, 75],
  [11, 2038, 77],
  [11, 2039, 78],
  [11, 2040, 45],
  [11, 2041, 43],
  [12, 4084, 44],
  [12, 4085, 79],
  [12, 4086, 42],
  [12, 4087, 41],
  [12, 4088, 80],
  [12, 4089, 40],
  [13, 8180, 81],
  [13, 8181, 39],
  [13, 8182, 82],
  [13, 8183, 38],
  [13, 8184, 83],
  [14, 16370, 37],
  [14, 16371, 35],
  [14, 16372, 85],
  [14, 16373, 33],
  [14, 16374, 36],
  [14, 16375, 34],
  [14, 16376, 84],
  [14, 16377, 32],
  [15, 32756, 87],
  [15, 32757, 89],
  [15, 32758, 30],
  [15, 32759, 31],
  [16, 65520, 86],
  [16, 65521, 29],
  [16, 65522, 26],
  [16, 65523, 27],
  [16, 65524, 28],
  [16, 65525, 24],
  [16, 65526, 88],
  [17, 131054, 25],
  [17, 131055, 22],
  [17, 131056, 23],
  [18, 262114, 90],
  [18, 262115, 21],
  [18, 262116, 19],
  [18, 262117, 3],
  [18, 262118, 1],
  [18, 262119, 2],
  [18, 262120, 0],
  [19, 524242, 98],
  [19, 524243, 99],
  [19, 524244, 100],
  [19, 524245, 101],
  [19, 524246, 102],
  [19, 524247, 117],
  [19, 524248, 97],
  [19, 524249, 91],
  [19, 524250, 92],
  [19, 524251, 93],
  [19, 524252, 94],
  [19, 524253, 95],
  [19, 524254, 96],
  [19, 524255, 104],
  [19, 524256, 111],
  [19, 524257, 112],
  [19, 524258, 113],
  [19, 524259, 114],
  [19, 524260, 115],
  [19, 524261, 116],
  [19, 524262, 110],
  [19, 524263, 105],
  [19, 524264, 106],
  [19, 524265, 107],
  [19, 524266, 108],
  [19, 524267, 109],
  [19, 524268, 118],
  [19, 524269, 6],
  [19, 524270, 8],
  [19, 524271, 9],
  [19, 524272, 10],
  [19, 524273, 5],
  [19, 524274, 103],
  [19, 524275, 120],
  [19, 524276, 119],
  [19, 524277, 4],
  [19, 524278, 7],
  [19, 524279, 15],
  [19, 524280, 16],
  [19, 524281, 18],
  [19, 524282, 20],
  [19, 524283, 17],
  [19, 524284, 11],
  [19, 524285, 12],
  [19, 524286, 14],
  [19, 524287, 13]
], I3 = [_3, y3, x3, v3, E3, S3, T3, b3, A3, C3, R3], L3 = [!1, !1, !0, !0, !1, !1, !0, !0, !0, !0, !0], Bf = 4, Ff = 2, pr = {
  findOffset: function(r, e) {
    let t = 0, i = e[t][0], s = r.read(i);
    for (; s !== e[t][1]; ) {
      let n = e[++t][0] - i;
      i = e[t][0], s <<= n, s |= r.read(n);
    }
    return t;
  },
  signValues: function(r, e, t, i) {
    for (let s = t; s < t + i; s++)
      e[s] && r.read(1) && (e[s] = -e[s]);
  },
  getEscape: function(r, e) {
    let t = 4;
    for (; r.read(1); )
      t++;
    let i = r.read(t) | 1 << t;
    return e < 0 ? -i : i;
  },
  decodeScaleFactor: function(r) {
    let e = this.findOffset(r, Mf);
    return Mf[e][2];
  },
  decodeSpectralData: function(r, e, t, i) {
    let s = I3[e - 1], n = this.findOffset(r, s);
    if (t[i] = s[n][2], t[i + 1] = s[n][3], e < 5 && (t[i + 2] = s[n][4], t[i + 3] = s[n][5]), e < 11)
      L3[e - 1] && this.signValues(r, t, i, e < 5 ? Bf : Ff);
    else if (e === 11 || e > 15)
      this.signValues(r, t, i, e < 5 ? Bf : Ff), Math.abs(t[i]) === 16 && (t[i] = this.getEscape(r, t[i])), Math.abs(t[i + 1]) === 16 && (t[i + 1] = this.getEscape(r, t[i + 1]));
    else
      throw new Error("Huffman: unknown spectral codebook: " + e);
  }
};
function Od(r) {
  this.maxBands = O3[r.sampleIndex], this.nFilt = new Int32Array(8), this.length = new Array(8), this.direction = new Array(8), this.order = new Array(8), this.coef = new Array(8);
  for (let e = 0; e < 8; e++) {
    this.length[e] = new Int32Array(4), this.direction[e] = new Array(4), this.order[e] = new Int32Array(4), this.coef[e] = new Array(4);
    for (let t = 0; t < 4; t++)
      this.coef[e][t] = new Float32Array(h0);
  }
  this.lpc = new Float32Array(h0), this.tmp = new Float32Array(h0);
}
const h0 = 20, D3 = [1, 4, 3], P3 = [2, 6, 5], k3 = [0, -0.43388373, 0.64278758, 0.34202015], w3 = [
  0,
  -0.43388373,
  -0.7818315,
  -0.9749279,
  0.98480773,
  0.86602539,
  0.64278758,
  0.34202015
], M3 = [
  0,
  -0.2079117,
  -0.40673664,
  -0.58778524,
  0.67369562,
  0.52643216,
  0.36124167,
  0.18374951
], B3 = [
  0,
  -0.2079117,
  -0.40673664,
  -0.58778524,
  -0.74314481,
  -0.86602539,
  -0.95105654,
  -0.99452192,
  0.99573416,
  0.96182561,
  0.8951633,
  0.7980172,
  0.67369562,
  0.52643216,
  0.36124167,
  0.18374951
], F3 = [w3, B3, k3, M3], O3 = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39];
Od.prototype.decode = function(r, e) {
  let t = e.windowCount, i = e.windowSequence === 2 ? D3 : P3;
  for (let s = 0; s < t; s++)
    if (this.nFilt[s] = r.read(i[0]), this.nFilt[s]) {
      let n = r.read(1), a = this.nFilt[s], o = this.length[s], c = this.order[s], l = this.direction[s], d = this.coef[s];
      for (let h = 0; h < a; h++) {
        if (o[h] = r.read(i[1]), (c[h] = r.read(i[2])) > 20)
          throw new Error("TNS filter out of range: " + c[h]);
        if (c[h]) {
          l[h] = !!r.read(1);
          let u = r.read(1), f = n + 3 - u, p = 2 * u + n, m = F3[p], g = c[h], x = d[h];
          for (let _ = 0; _ < g; _++)
            x[_] = m[r.read(f)];
        }
      }
    }
};
Od.prototype.process = function(r, e, t) {
  let i = Math.min(this.maxBands, r.maxSFB), s = this.lpc, n = this.tmp, a = r.info, o = a.windowCount;
  for (let c = 0; c < o; c++) {
    a.swbCount;
    let l = this.nFilt[c], d = this.length[c], h = this.order[c], u = this.coef[c], f = this.direction[c], p, m;
    for (let g = 0; g < l; g++) {
      let x = _, _ = Math.max(0, n - d[g]), v = h[g];
      if (v === 0) continue;
      let E = u[g];
      for (p = 0; p < v; p++) {
        let L = -E[p];
        s[p] = L;
        for (let R = 0, D = p + 1 >> 1; R < D; R++) {
          let M = s[R], w = s[p - 1 - R];
          s[R] = M + L * w, s[p - 1 - R] = w + L * M;
        }
      }
      let b = a.swbOffsets[Math.min(_, i)], A = a.swbOffsets[Math.min(x, i)], C, I = 1;
      if (!((C = A - b) <= 0))
        if (f[g] && (I = -1, b = A - 1), b += c * 128, t)
          for (m = 0; m < C; m++, b += I)
            for (p = 1; p <= Math.min(m, v); p++)
              e[b] -= e[b - p * I] * s[p - 1];
        else
          for (m = 0; m < C; m++, b += I) {
            for (n[0] = e[b], p = 1; p <= Math.min(m, v); p++)
              e[b] += n[p] * s[p - 1];
            for (p = v; p > 0; p--)
              n[p] = n[p - 1];
          }
    }
  }
};
class ue {
  constructor(e) {
    this.info = new G3(), this.bandTypes = new Int32Array(u0), this.sectEnd = new Int32Array(u0), this.data = new Float32Array(e.frameLength), this.scaleFactors = new Float32Array(u0), this.randomState = 523124044, this.tns = new Od(e), this.specBuf = new Int32Array(4);
  }
  decode(e, t, i) {
    if (this.globalGain = e.read(8), i || this.info.decode(e, t, i), this.decodeBandTypes(e, t), this.decodeScaleFactors(e), this.pulsePresent = e.read(1), this.pulsePresent) {
      if (this.info.windowSequence === ue.EIGHT_SHORT_SEQUENCE)
        throw new Error("Pulse tool not allowed in eight short sequence.");
      this.decodePulseData(e);
    }
    if (this.tnsPresent = e.read(1), this.tnsPresent && this.tns.decode(e, this.info), this.gainPresent = e.read(1), this.gainPresent)
      throw new Error("TODO: decode gain control/SSR");
    this.decodeSpectralData(e);
  }
  decodeBandTypes(e, t) {
    let i = this.info.windowSequence === ue.EIGHT_SHORT_SEQUENCE ? 3 : 5, s = this.info.groupCount, n = this.info.maxSFB, a = this.bandTypes, o = this.sectEnd, c = 0, l = (1 << i) - 1;
    for (let d = 0; d < s; d++) {
      let h = 0;
      for (; h < n; ) {
        let u = h, f = e.read(4);
        if (f === 12)
          throw new Error("Invalid band type: 12");
        let p;
        for (; (p = e.read(i)) === l; )
          u += p;
        if (u += p, u > n)
          throw new Error("Too many bands (" + u + " > " + n + ")");
        for (; h < u; h++)
          a[c] = f, o[c++] = u;
      }
    }
  }
  decodeScaleFactors(e) {
    let t = this.info.groupCount, i = this.info.maxSFB, s = [this.globalGain, this.globalGain - 90, 0], n = 0, a = !0, o = this.scaleFactors, c = this.sectEnd, l = this.bandTypes, d;
    for (let h = 0; h < t; h++)
      for (let u = 0; u < i; ) {
        let f = c[n];
        switch (l[n]) {
          case ue.ZERO_BT:
            for (; u < f; u++, n++)
              o[n] = 0;
            break;
          case ue.INTENSITY_BT:
          case ue.INTENSITY_BT2:
            for (; u < f; u++, n++)
              s[2] += pr.decodeScaleFactor(e) - f0, d = Math.min(Math.max(s[2], -155), 100), o[n] = d0[-d + p0];
            break;
          case ue.NOISE_BT:
            for (; u < f; u++, n++)
              a ? (s[1] += e.read(9) - 256, a = !1) : s[1] += pr.decodeScaleFactor(e) - f0, d = Math.min(Math.max(s[1], -100), 155), o[n] = -d0[d + p0];
            break;
          default:
            for (; u < f; u++, n++) {
              if (s[0] += pr.decodeScaleFactor(e) - f0, s[0] > 255)
                throw new Error("Scalefactor out of range: " + s[0]);
              o[n] = d0[s[0] - 100 + p0];
            }
            break;
        }
      }
  }
  decodePulseData(e) {
    let t = e.read(2) + 1, i = e.read(6);
    if (i >= this.info.swbCount)
      throw new Error("Pulse SWB out of range: " + i);
    if ((!this.pulseOffset || this.pulseOffset.length !== t) && (this.pulseOffset = new Int32Array(t), this.pulseAmp = new Int32Array(t)), this.pulseOffset[0] = this.info.swbOffsets[i] + e.read(5), this.pulseAmp[0] = e.read(4), this.pulseOffset[0] > 1023)
      throw new Error("Pulse offset out of range: " + this.pulseOffset[0]);
    for (let s = 1; s < t; s++) {
      if (this.pulseOffset[s] = e.read(5) + this.pulseOffset[s - 1], this.pulseOffset[s] > 1023)
        throw new Error("Pulse offset out of range: " + this.pulseOffset[s]);
      this.pulseAmp[s] = e.read(4);
    }
  }
  decodeSpectralData(e) {
    let t = this.data, i = this.info, s = i.maxSFB, n = i.groupCount, a = i.swbOffsets, o = this.bandTypes, c = this.scaleFactors, l = this.specBuf, d = 0, h = 0, u, f;
    for (let p = 0; p < n; p++) {
      let m = i.groupLength[p];
      for (let g = 0; g < s; g++, h++) {
        let x = o[h], _ = d + a[g], v = a[g + 1] - a[g];
        if (x === ue.ZERO_BT || x === ue.INTENSITY_BT || x === ue.INTENSITY_BT2)
          for (u = 0; u < m; u++, _ += 128)
            for (let E = _; E < _ + v; E++)
              t[E] = 0;
        else if (x === ue.NOISE_BT)
          for (u = 0; u < m; u++, _ += 128) {
            let E = 0;
            for (f = 0; f < v; f++)
              this.randomState = this.randomState * 1015568748 | 0, t[_ + f] = this.randomState, E += t[_ + f] * t[_ + f];
            let b = c[h] / Math.sqrt(E);
            for (f = 0; f < v; f++)
              t[_ + f] *= b;
          }
        else
          for (u = 0; u < m; u++, _ += 128) {
            let E = x >= ue.FIRST_PAIR_BT ? 2 : 4;
            for (f = 0; f < v; f += E) {
              pr.decodeSpectralData(e, x, l, 0);
              for (let b = 0; b < E; b++)
                t[_ + f + b] = l[b] > 0 ? wf[l[b]] : -wf[-l[b]], t[_ + f + b] *= c[h];
            }
          }
      }
      d += m << 7;
    }
    if (this.pulsePresent)
      throw new Error("TODO: add pulse data");
  }
}
ue.ZERO_BT = 0;
ue.FIRST_PAIR_BT = 5;
ue.ESC_BT = 11;
ue.NOISE_BT = 13;
ue.INTENSITY_BT2 = 14;
ue.INTENSITY_BT = 15;
ue.ONLY_LONG_SEQUENCE = 0;
ue.LONG_START_SEQUENCE = 1;
ue.EIGHT_SHORT_SEQUENCE = 2;
ue.LONG_STOP_SEQUENCE = 3;
const u0 = 120, N3 = 8, f0 = 60, p0 = 200;
class G3 {
  constructor() {
    this.windowShape = new Int32Array(2), this.windowSequence = ue.ONLY_LONG_SEQUENCE, this.groupLength = new Int32Array(N3), this.ltpData1Present = !1, this.ltpData2Present = !1;
  }
  decode(e, t, i) {
    if (e.advance(1), this.windowSequence = e.read(2), this.windowShape[0] = this.windowShape[1], this.windowShape[1] = e.read(1), this.groupCount = 1, this.groupLength[0] = 1, this.windowSequence === ue.EIGHT_SHORT_SEQUENCE) {
      this.maxSFB = e.read(4);
      for (let s = 0; s < 7; s++)
        e.read(1) ? this.groupLength[this.groupCount - 1]++ : (this.groupCount++, this.groupLength[this.groupCount - 1] = 1);
      this.windowCount = 8, this.swbOffsets = u3[t.sampleIndex], this.swbCount = f3[t.sampleIndex], this.predictorPresent = !1;
    } else
      this.maxSFB = e.read(6), this.windowCount = 1, this.swbOffsets = h3[t.sampleIndex], this.swbCount = p3[t.sampleIndex], this.predictorPresent = !!e.read(1), this.predictorPresent && this.decodePrediction(e, t, i);
  }
  decodePrediction(e, t, i) {
    throw new Error("Prediction not implemented.");
  }
}
function Ia(r) {
  this.ms_used = [], this.left = new ue(r), this.right = new ue(r);
}
const Of = 128, U3 = 0, V3 = 1, W3 = 2;
Ia.prototype.decode = function(r, e) {
  let t = this.left, i = this.right, s = this.ms_used;
  if (this.commonWindow = !!r.read(1), this.commonWindow) {
    t.info.decode(r, e, !0), i.info = t.info;
    let n = r.read(2);
    switch (this.maskPresent = !!n, n) {
      case V3:
        {
          let a = t.info.groupCount * t.info.maxSFB;
          for (let o = 0; o < a; o++)
            s[o] = !!r.read(1);
        }
        break;
      case U3:
      case W3:
        {
          let a = !!n;
          for (let o = 0; o < Of; o++)
            s[o] = a;
        }
        break;
      default:
        throw new Error("Reserved ms mask type: " + n);
    }
  } else
    for (let n = 0; n < Of; n++)
      s[n] = !1;
  t.decode(r, e, this.commonWindow), i.decode(r, e, this.commonWindow);
};
class Tt {
  constructor(e) {
    this.ics = new ue(e), this.channelPair = new Array(8), this.idSelect = new Int32Array(8), this.chSelect = new Int32Array(8), this.gain = new Array(16);
  }
  decode(e, t) {
    let i = this.channelPair, s = this.idSelect, n = this.chSelect;
    this.couplingPoint = 2 * e.read(1), this.coupledCount = e.read(3);
    let a = 0, o = 0;
    for (; o <= this.coupledCount; o++)
      a++, i[o] = e.read(1), s[o] = e.read(4), i[o] ? (n[o] = e.read(2), n[o] === 3 && a++) : n[o] = 2;
    this.couplingPoint += e.read(1), this.couplingPoint |= this.couplingPoint >>> 1;
    let c = e.read(1), l = H3[e.read(2)];
    this.ics.decode(e, t, !1);
    let d = this.ics.info.groupCount, h = this.ics.info.maxSFB, u = this.ics.bandTypes;
    for (o = 0; o < a; o++) {
      let f = 0, p = 1, m = 0, g = 1;
      o > 0 && (p = this.couplingPoint === Tt.AFTER_IMDCT ? 1 : e.read(1), m = p ? pr.decodeScaleFactor(e) - 60 : 0, g = Math.pow(l, -m));
      let x = this.gain[o] = new Float32Array(120);
      if (this.couplingPoint === Tt.AFTER_IMDCT)
        x[0] = g;
      else
        for (let _ = 0; _ < d; _++)
          for (let v = 0; v < h; v++)
            if (u[f] !== ue.ZERO_BT) {
              if (p === 0) {
                let E = pr.decodeScaleFactor(e) - 60;
                if (E !== 0) {
                  let b = 1;
                  E = m += E, c || (b -= 2 * (E & 1), E >>>= 1), g = Math.pow(l, -E) * b;
                }
              }
              x[f++] = g;
            }
    }
  }
  applyIndependentCoupling(e, t) {
    let i = this.gain[e][0], s = this.ics.data;
    for (let n = 0; n < t.length; n++)
      t[n] += i * s[n];
  }
  applyDependentCoupling(e, t) {
    let i = this.ics.info, s = i.swbOffsets, n = i.groupCount, a = i.maxSFB, o = this.ics.bandTypes, c = this.ics.data, l = 0, d = 0, h = this.gain[e];
    for (let u = 0; u < n; u++) {
      let f = i.groupLength[u];
      for (let p = 0; p < a; p++, l++)
        if (o[l] !== ue.ZERO_BT) {
          let m = h[l];
          for (let g = 0; g < f; g++)
            for (let x = s[p]; x < s[p + 1]; x++)
              t[d + g * 128 + x] += m * c[d + g * 128 + x];
        }
      d += f * 128;
    }
  }
}
Tt.BEFORE_TNS = 0;
Tt.AFTER_TNS = 1;
Tt.AFTER_IMDCT = 2;
const H3 = new Float32Array([
  1.0905077326652577,
  1.189207115002721,
  1.4142135623730951,
  2
]), Z3 = [
  [0.031249997702054, 11984224612e-15],
  [0.031249813866531, 107857810004e-15],
  [0.031249335895858, 203730380198e-15],
  [0.031248563794535, 299601032804e-15],
  [0.031247497569829, 395468865451e-15],
  [0.031246137231775, 491332975794e-15],
  [0.031244482793177, 587192461525e-15],
  [0.031242534269608, 683046420376e-15],
  [0.031240291679407, 778893950134e-15],
  [0.031237755043684, 874734148645e-15],
  [0.031234924386313, 970566113826e-15],
  [0.031231799733938, 0.001066388943669],
  [0.03122838111597, 0.001162201736253],
  [0.031224668564585, 0.001258003589751],
  [0.031220662114728, 0.001353793602441],
  [0.031216361804108, 0.00144957087271],
  [0.031211767673203, 0.001545334499065],
  [0.031206879765253, 0.001641083580144],
  [0.031201698126266, 0.001736817214719],
  [0.031196222805014, 0.001832534501709],
  [0.031190453853031, 0.001928234540186],
  [0.031184391324617, 0.002023916429386],
  [0.031178035276836, 0.002119579268713],
  [0.031171385769513, 0.002215222157753],
  [0.031164442865236, 0.002310844196278],
  [0.031157206629353, 0.002406444484258],
  [0.031149677129975, 0.002502022121865],
  [0.031141854437973, 0.002597576209488],
  [0.031133738626977, 0.002693105847734],
  [0.031125329773375, 0.002788610137442],
  [0.031116627956316, 0.002884088179689],
  [0.031107633257703, 0.002979539075801],
  [0.0310983457622, 0.003074961927355],
  [0.031088765557222, 0.003170355836197],
  [0.031078892732942, 0.003265719904442],
  [0.031068727382288, 0.003361053234488],
  [0.031058269600939, 0.003456354929021],
  [0.031047519487329, 0.003551624091024],
  [0.03103647714264, 0.00364685982379],
  [0.031025142670809, 0.003742061230921],
  [0.031013516178519, 0.003837227416347],
  [0.031001597775203, 0.003932357484328],
  [0.030989387573042, 0.004027450539462],
  [0.030976885686963, 0.004122505686697],
  [0.030964092234638, 0.00421752203134],
  [0.030951007336485, 0.004312498679058],
  [0.030937631115663, 0.004407434735897],
  [0.030923963698074, 0.004502329308281],
  [0.030910005212362, 0.004597181503027],
  [0.030895755789908, 0.00469199042735],
  [0.030881215564835, 0.004786755188872],
  [0.030866384674, 0.004881474895632],
  [0.030851263256996, 0.00497614865609],
  [0.030835851456154, 0.005070775579142],
  [0.030820149416533, 0.005165354774124],
  [0.030804157285929, 0.005259885350819],
  [0.030787875214864, 0.005354366419469],
  [0.030771303356593, 0.005448797090784],
  [0.030754441867095, 0.005543176475946],
  [0.030737290905077, 0.005637503686619],
  [0.030719850631972, 0.005731777834961],
  [0.030702121211932, 0.005825998033626],
  [0.030684102811835, 0.00592016339578],
  [0.030665795601276, 0.006014273035101],
  [0.03064719975257, 0.006108326065793],
  [0.030628315440748, 0.006202321602594],
  [0.030609142843557, 0.006296258760782],
  [0.030589682141455, 0.006390136656185],
  [0.030569933517616, 0.006483954405188],
  [0.030549897157919, 0.006577711124743],
  [0.030529573250956, 0.006671405932375],
  [0.030508961988022, 0.006765037946194],
  [0.030488063563118, 0.0068586062849],
  [0.030466878172949, 0.006952110067791],
  [0.030445406016919, 0.007045548414774],
  [0.030423647297133, 0.007138920446372],
  [0.030401602218392, 0.007232225283733],
  [0.030379270988192, 0.007325462048634],
  [0.030356653816724, 0.007418629863497],
  [0.030333750916869, 0.00751172785139],
  [0.030310562504198, 0.00760475513604],
  [0.030287088796968, 0.007697710841838],
  [0.030263330016124, 0.007790594093851],
  [0.030239286385293, 0.007883404017824],
  [0.030214958130781, 0.007976139740197],
  [0.030190345481576, 0.008068800388104],
  [0.030165448669342, 0.00816138508939],
  [0.030140267928416, 0.00825389297261],
  [0.030114803495809, 0.008346323167047],
  [0.030089055611203, 0.008438674802711],
  [0.030063024516947, 0.008530947010354],
  [0.030036710458054, 0.008623138921475],
  [0.030010113682202, 0.008715249668328],
  [0.029983234439732, 0.008807278383932],
  [0.02995607298364, 0.008899224202078],
  [0.02992862956958, 0.008991086257336],
  [0.02990090445586, 0.009082863685067],
  [0.029872897903441, 0.009174555621425],
  [0.029844610175929, 0.009266161203371],
  [0.029816041539579, 0.009357679568679],
  [0.029787192263292, 0.009449109855944],
  [0.029758062618606, 0.009540451204587],
  [0.029728652879702, 0.009631702754871],
  [0.029698963323395, 0.0097228636479],
  [0.029668994229134, 0.009813933025633],
  [0.029638745879, 0.009904910030891],
  [0.029608218557702, 0.009995793807363],
  [0.029577412552575, 0.010086583499618],
  [0.029546328153577, 0.010177278253107],
  [0.029514965653285, 0.010267877214177],
  [0.029483325346896, 0.010358379530076],
  [0.02945140753222, 0.010448784348962],
  [0.029419212509679, 0.010539090819911],
  [0.029386740582307, 0.010629298092923],
  [0.02935399205574, 0.010719405318933],
  [0.02932096723822, 0.010809411649818],
  [0.02928766644059, 0.010899316238403],
  [0.02925408997629, 0.010989118238474],
  [0.029220238161353, 0.011078816804778],
  [0.029186111314406, 0.011168411093039],
  [0.029151709756664, 0.011257900259961],
  [0.029117033811927, 0.011347283463239],
  [0.029082083806579, 0.011436559861563],
  [0.029046860069582, 0.01152572861463],
  [0.029011362932476, 0.01161478888315],
  [0.028975592729373, 0.011703739828853],
  [0.028939549796957, 0.0117925806145],
  [0.028903234474475, 0.011881310403886],
  [0.028866647103744, 0.011969928361855],
  [0.028829788029135, 0.012058433654299],
  [0.028792657597583, 0.012146825448172],
  [0.028755256158571, 0.012235102911499],
  [0.028717584064137, 0.012323265213377],
  [0.028679641668864, 0.01241131152399],
  [0.028641429329882, 0.012499241014612],
  [0.028602947406859, 0.012587052857618],
  [0.028564196262001, 0.012674746226488],
  [0.02852517626005, 0.012762320295819],
  [0.028485887768276, 0.012849774241331],
  [0.028446331156478, 0.012937107239875],
  [0.028406506796976, 0.013024318469437],
  [0.028366415064615, 0.013111407109155],
  [0.028326056336751, 0.013198372339315],
  [0.028285430993258, 0.013285213341368],
  [0.028244539416515, 0.013371929297933],
  [0.028203381991411, 0.013458519392807],
  [0.028161959105334, 0.013544982810971],
  [0.028120271148172, 0.013631318738598],
  [0.028078318512309, 0.013717526363062],
  [0.028036101592619, 0.013803604872943],
  [0.027993620786463, 0.013889553458039],
  [0.027950876493687, 0.013975371309367],
  [0.027907869116616, 0.014061057619178],
  [0.027864599060052, 0.014146611580959],
  [0.02782106673127, 0.014232032389445],
  [0.027777272540012, 0.014317319240622],
  [0.027733216898487, 0.014402471331737],
  [0.027688900221361, 0.014487487861307],
  [0.027644322925762, 0.014572368029123],
  [0.027599485431266, 0.014657111036262],
  [0.027554388159903, 0.01474171608509],
  [0.027509031536144, 0.014826182379271],
  [0.027463415986904, 0.014910509123778],
  [0.027417541941533, 0.014994695524894],
  [0.027371409831816, 0.015078740790225],
  [0.027325020091965, 0.015162644128704],
  [0.027278373158618, 0.015246404750603],
  [0.027231469470833, 0.015330021867534],
  [0.027184309470088, 0.01541349469246],
  [0.027136893600268, 0.015496822439704],
  [0.027089222307671, 0.015580004324954],
  [0.027041296040997, 0.015663039565269],
  [0.026993115251345, 0.015745927379091],
  [0.026944680392213, 0.015828666986247],
  [0.026895991919487, 0.015911257607961],
  [0.026847050291442, 0.015993698466859],
  [0.026797855968734, 0.016075988786976],
  [0.026748409414401, 0.016158127793763],
  [0.026698711093851, 0.016240114714099],
  [0.026648761474864, 0.016321948776289],
  [0.026598561027585, 0.016403629210082],
  [0.026548110224519, 0.016485155246669],
  [0.02649740954053, 0.016566526118696],
  [0.02644645945283, 0.016647741060271],
  [0.026395260440982, 0.016728799306966],
  [0.02634381298689, 0.016809700095831],
  [0.026292117574797, 0.016890442665397],
  [0.02624017469128, 0.016971026255683],
  [0.026187984825246, 0.017051450108208],
  [0.026135548467924, 0.01713171346599],
  [0.026082866112867, 0.01721181557356],
  [0.026029938255941, 0.017291755676967],
  [0.025976765395322, 0.017371533023784],
  [0.025923348031494, 0.017451146863116],
  [0.025869686667242, 0.017530596445607],
  [0.025815781807646, 0.017609881023449],
  [0.02576163396008, 0.017688999850383],
  [0.025707243634204, 0.017767952181715],
  [0.02565261134196, 0.017846737274313],
  [0.025597737597568, 0.017925354386623],
  [0.025542622917522, 0.018003802778671],
  [0.025487267820581, 0.018082081712071],
  [0.025431672827768, 0.018160190450031],
  [0.025375838462365, 0.018238128257362],
  [0.025319765249906, 0.018315894400484],
  [0.025263453718173, 0.018393488147432],
  [0.025206904397193, 0.018470908767865],
  [0.025150117819228, 0.01854815553307],
  [0.025093094518776, 0.018625227715971],
  [0.025035835032562, 0.018702124591135],
  [0.024978339899534, 0.01877884543478],
  [0.024920609660858, 0.01885538952478],
  [0.024862644859912, 0.018931756140672],
  [0.024804446042284, 0.019007944563666],
  [0.024746013755764, 0.019083954076646],
  [0.024687348550337, 0.019159783964183],
  [0.024628450978184, 0.019235433512536],
  [0.02456932159367, 0.019310902009663],
  [0.024509960953345, 0.019386188745225],
  [0.024450369615932, 0.019461293010596],
  [0.024390548142329, 0.019536214098866],
  [0.024330497095598, 0.019610951304848],
  [0.024270217040961, 0.019685503925087],
  [0.024209708545799, 0.019759871257867],
  [0.024148972179639, 0.019834052603212],
  [0.024088008514157, 0.019908047262901],
  [0.024026818123164, 0.019981854540467],
  [0.023965401582609, 0.020055473741208],
  [0.023903759470567, 0.020128904172192],
  [0.023841892367236, 0.020202145142264],
  [0.023779800854935, 0.020275195962052],
  [0.023717485518092, 0.020348055943974],
  [0.023654946943242, 0.020420724402244],
  [0.023592185719023, 0.020493200652878],
  [0.023529202436167, 0.020565484013703],
  [0.023465997687496, 0.020637573804361],
  [0.023402572067918, 0.020709469346314],
  [0.023338926174419, 0.020781169962854],
  [0.023275060606058, 0.020852674979108],
  [0.023210975963963, 0.020923983722044],
  [0.023146672851322, 0.020995095520475],
  [0.02308215187338, 0.021066009705072],
  [0.023017413637435, 0.021136725608363],
  [0.022952458752826, 0.021207242564742],
  [0.022887287830934, 0.021277559910478],
  [0.022821901485173, 0.021347676983716],
  [0.022756300330983, 0.021417593124488],
  [0.022690484985827, 0.021487307674717],
  [0.022624456069185, 0.021556819978223],
  [0.022558214202547, 0.021626129380729],
  [0.022491760009405, 0.021695235229869],
  [0.022425094115252, 0.021764136875192],
  [0.022358217147572, 0.021832833668171],
  [0.022291129735838, 0.021901324962204],
  [0.022223832511501, 0.021969610112625],
  [0.022156326107988, 0.022037688476709],
  [0.022088611160696, 0.022105559413676],
  [0.022020688306983, 0.022173222284699],
  [0.021952558186166, 0.022240676452909],
  [0.02188422143951, 0.022307921283403],
  [0.021815678710228, 0.022374956143245],
  [0.021746930643469, 0.022441780401478],
  [0.021677977886316, 0.022508393429127],
  [0.02160882108778, 0.022574794599206],
  [0.02153946089879, 0.022640983286719],
  [0.02146989797219, 0.022706958868676],
  [0.021400132962735, 0.022772720724087],
  [0.021330166527077, 0.022838268233979],
  [0.021259999323769, 0.022903600781391],
  [0.02118963201325, 0.022968717751391],
  [0.021119065257845, 0.023033618531071],
  [0.021048299721754, 0.023098302509561],
  [0.02097733607105, 0.023162769078031],
  [0.02090617497367, 0.023227017629698],
  [0.020834817099409, 0.023291047559828],
  [0.020763263119915, 0.023354858265748],
  [0.02069151370868, 0.023418449146848],
  [0.020619569541038, 0.023481819604585],
  [0.020547431294155, 0.023544969042494],
  [0.020475099647023, 0.023607896866186],
  [0.020402575280455, 0.023670602483363],
  [0.020329858877078, 0.023733085303813],
  [0.020256951121327, 0.023795344739427],
  [0.020183852699437, 0.023857380204193],
  [0.020110564299439, 0.023919191114211],
  [0.02003708661115, 0.023980776887692],
  [0.019963420326171, 0.024042136944968],
  [0.019889566137877, 0.024103270708495],
  [0.019815524741412, 0.024164177602859],
  [0.019741296833681, 0.024224857054779],
  [0.019666883113346, 0.02428530849312],
  [0.019592284280817, 0.024345531348888],
  [0.019517501038246, 0.024405525055242],
  [0.019442534089523, 0.0244652890475],
  [0.019367384140264, 0.024524822763141],
  [0.019292051897809, 0.024584125641809],
  [0.019216538071215, 0.024643197125323],
  [0.019140843371246, 0.024702036657681],
  [0.019064968510369, 0.024760643685063],
  [0.018988914202748, 0.024819017655836],
  [0.018912681164234, 0.024877158020562],
  [0.018836270112363, 0.024935064232003],
  [0.018759681766343, 0.024992735745123],
  [0.018682916847054, 0.025050172017095],
  [0.018605976077037, 0.025107372507308],
  [0.018528860180486, 0.025164336677369],
  [0.018451569883247, 0.02522106399111],
  [0.018374105912805, 0.025277553914591],
  [0.01829646899828, 0.025333805916107],
  [0.018218659870421, 0.025389819466194],
  [0.018140679261596, 0.02544559403763],
  [0.01806252790579, 0.025501129105445],
  [0.017984206538592, 0.02555642414692],
  [0.017905715897192, 0.025611478641598],
  [0.017827056720375, 0.025666292071285],
  [0.017748229748511, 0.025720863920056],
  [0.01766923572355, 0.02577519367426],
  [0.017590075389012, 0.025829280822525],
  [0.017510749489986, 0.025883124855762],
  [0.017431258773116, 0.02593672526717],
  [0.0173516039866, 0.025990081552242],
  [0.01727178588018, 0.026043193208768],
  [0.017191805205132, 0.026096059736841],
  [0.017111662714267, 0.026148680638861],
  [0.017031359161915, 0.026201055419541],
  [0.016950895303924, 0.026253183585908],
  [0.016870271897651, 0.026305064647313],
  [0.016789489701954, 0.026356698115431],
  [0.016708549477186, 0.026408083504269],
  [0.016627451985187, 0.026459220330167],
  [0.016546197989277, 0.026510108111806],
  [0.01646478825425, 0.026560746370212],
  [0.016383223546365, 0.026611134628757],
  [0.016301504633341, 0.026661272413168],
  [0.016219632284346, 0.02671115925153],
  [0.016137607269996, 0.026760794674288],
  [0.01605543036234, 0.026810178214254],
  [0.015973102334858, 0.026859309406613],
  [0.015890623962454, 0.026908187788922],
  [0.015807996021446, 0.026956812901119],
  [0.015725219289558, 0.027005184285527],
  [0.015642294545918, 0.027053301486856],
  [0.015559222571044, 0.027101164052208],
  [0.015476004146842, 0.027148771531083],
  [0.015392640056594, 0.02719612347538],
  [0.015309131084956, 0.027243219439406],
  [0.015225478017946, 0.027290058979875],
  [0.015141681642938, 0.027336641655915],
  [0.015057742748656, 0.027382967029073],
  [0.014973662125164, 0.027429034663317],
  [0.014889440563862, 0.02747484412504],
  [0.014805078857474, 0.027520394983066],
  [0.014720577800046, 0.027565686808654],
  [0.014635938186934, 0.027610719175499],
  [0.014551160814797, 0.02765549165974],
  [0.014466246481592, 0.02770000383996],
  [0.014381195986567, 0.027744255297195],
  [0.014296010130247, 0.027788245614933],
  [0.014210689714436, 0.02783197437912],
  [0.014125235542201, 0.027875441178165],
  [0.01403964841787, 0.027918645602941],
  [0.01395392914702, 0.027961587246792],
  [0.013868078536476, 0.028004265705534],
  [0.013782097394294, 0.028046680577462],
  [0.013695986529763, 0.028088831463351],
  [0.01360974675339, 0.028130717966461],
  [0.013523378876898, 0.02817233969254],
  [0.013436883713214, 0.028213696249828],
  [0.013350262076462, 0.028254787249062],
  [0.01326351478196, 0.028295612303478],
  [0.013176642646205, 0.028336171028814],
  [0.013089646486871, 0.028376463043317],
  [0.013002527122799, 0.028416487967743],
  [0.01291528537399, 0.028456245425361],
  [0.012827922061597, 0.02849573504196],
  [0.012740438007915, 0.028534956445849],
  [0.012652834036379, 0.028573909267859],
  [0.01256511097155, 0.028612593141354],
  [0.012477269639111, 0.028651007702224],
  [0.012389310865858, 0.028689152588899],
  [0.012301235479693, 0.028727027442343],
  [0.012213044309615, 0.028764631906065],
  [0.012124738185712, 0.028801965626115],
  [0.012036317939156, 0.028839028251097],
  [0.011947784402191, 0.028875819432161],
  [0.01185913840813, 0.028912338823015],
  [0.011770380791341, 0.028948586079925],
  [0.011681512387245, 0.028984560861718],
  [0.011592534032306, 0.029020262829785],
  [0.011503446564022, 0.029055691648087],
  [0.011414250820918, 0.029090846983152],
  [0.011324947642537, 0.029125728504087],
  [0.011235537869437, 0.029160335882573],
  [0.011146022343175, 0.029194668792871],
  [0.011056401906305, 0.029228726911828],
  [0.010966677402371, 0.029262509918876],
  [0.010876849675891, 0.029296017496036],
  [0.010786919572361, 0.029329249327922],
  [0.010696887938235, 0.029362205101743],
  [0.010606755620926, 0.029394884507308],
  [0.010516523468793, 0.029427287237024],
  [0.010426192331137, 0.029459412985906],
  [0.010335763058187, 0.029491261451573],
  [0.010245236501099, 0.029522832334255],
  [0.010154613511943, 0.029554125336796],
  [0.010063894943698, 0.029585140164654],
  [0.00997308165024, 0.029615876525905],
  [0.00988217448634, 0.029646334131247],
  [0.00979117430765, 0.029676512694001],
  [0.009700081970699, 0.029706411930116],
  [0.009608898332881, 0.029736031558168],
  [0.009517624252453, 0.029765371299366],
  [0.009426260588521, 0.029794430877553],
  [0.009334808201034, 0.02982321001921],
  [0.009243267950778, 0.029851708453456],
  [0.009151640699363, 0.029879925912053],
  [0.00905992730922, 0.029907862129408],
  [0.008968128643591, 0.029935516842573],
  [0.00887624556652, 0.029962889791254],
  [0.008784278942845, 0.029989980717805],
  [0.008692229638191, 0.030016789367235],
  [0.008600098518961, 0.030043315487212],
  [0.008507886452329, 0.030069558828062],
  [0.00841559430623, 0.030095519142772],
  [0.008323222949351, 0.030121196186994],
  [0.008230773251129, 0.030146589719046],
  [0.008138246081733, 0.030171699499915],
  [0.008045642312067, 0.030196525293257],
  [0.00795296281375, 0.030221066865402],
  [0.007860208459119, 0.030245323985357],
  [0.007767380121212, 0.030269296424803],
  [0.007674478673766, 0.030292983958103],
  [0.007581504991203, 0.030316386362302],
  [0.007488459948628, 0.030339503417126],
  [0.007395344421816, 0.030362334904989],
  [0.007302159287206, 0.030384880610993],
  [0.007208905421891, 0.030407140322928],
  [0.007115583703613, 0.030429113831278],
  [0.007022195010752, 0.03045080092922],
  [0.006928740222316, 0.030472201412626],
  [0.006835220217939, 0.030493315080068],
  [0.006741635877866, 0.030514141732814],
  [0.006647988082948, 0.030534681174838],
  [0.006554277714635, 0.030554933212813],
  [0.006460505654964, 0.030574897656119],
  [0.006366672786553, 0.030594574316845],
  [0.006272779992593, 0.030613963009786],
  [0.006178828156839, 0.030633063552447],
  [0.006084818163601, 0.030651875765048],
  [0.005990750897737, 0.03067039947052],
  [0.005896627244644, 0.030688634494512],
  [0.00580244809025, 0.030706580665388],
  [0.005708214321004, 0.030724237814232],
  [0.005613926823871, 0.030741605774849],
  [0.005519586486321, 0.030758684383764],
  [0.005425194196321, 0.030775473480228],
  [0.005330750842327, 0.030791972906214],
  [0.005236257313276, 0.030808182506425],
  [0.005141714498576, 0.030824102128288],
  [0.005047123288102, 0.030839731621963],
  [0.004952484572181, 0.030855070840339],
  [0.004857799241589, 0.030870119639036],
  [0.004763068187541, 0.030884877876411],
  [0.004668292301681, 0.030899345413553],
  [0.004573472476075, 0.030913522114288],
  [0.004478609603205, 0.03092740784518],
  [0.004383704575956, 0.03094100247553],
  [0.00428875828761, 0.030954305877381],
  [0.004193771631837, 0.030967317925516],
  [0.004098745502689, 0.030980038497461],
  [0.004003680794587, 0.030992467473486],
  [0.003908578402316, 0.031004604736602],
  [0.003813439221017, 0.031016450172571],
  [0.003718264146176, 0.031028003669899],
  [0.003623054073616, 0.031039265119839],
  [0.003527809899492, 0.031050234416394],
  [0.003432532520278, 0.031060911456318],
  [0.00333722283276, 0.031071296139114],
  [0.003241881734029, 0.031081388367037],
  [0.003146510121474, 0.031091188045095],
  [0.003051108892766, 0.031100695081051],
  [0.00295567894586, 0.031109909385419],
  [0.002860221178978, 0.031118830871473],
  [0.002764736490604, 0.031127459455239],
  [0.002669225779478, 0.031135795055501],
  [0.002573689944583, 0.031143837593803],
  [0.002478129885137, 0.031151586994444],
  [0.002382546500589, 0.031159043184484],
  [0.002286940690606, 0.031166206093743],
  [0.002191313355067, 0.0311730756548],
  [0.002095665394051, 0.031179651802998],
  [0.001999997707835, 0.031185934476438],
  [0.001904311196878, 0.031191923615985],
  [0.00180860676182, 0.031197619165268],
  [0.001712885303465, 0.031203021070678],
  [0.001617147722782, 0.03120812928137],
  [0.001521394920889, 0.031212943749264],
  [0.001425627799047, 0.031217464429043],
  [0.001329847258653, 0.031221691278159],
  [0.001234054201231, 0.031225624256825],
  [0.00113824952842, 0.031229263328024],
  [0.001042434141971, 0.031232608457502],
  [946608943736e-15, 0.031235659613775],
  [850774835656e-15, 0.031238416768124],
  [754932719759e-15, 0.031240879894597],
  [659083498149e-15, 0.03124304897001],
  [563228072993e-15, 0.031244923973948],
  [46736734652e-14, 0.031246504888762],
  [371502221008e-15, 0.031247791699571],
  [275633598775e-15, 0.031248784394264],
  [179762382174e-15, 0.031249482963498],
  [83889473581e-15, 0.031249887400697]
], $3 = [
  [0.088387931675923, 271171628935e-15],
  [0.088354655998507, 0.002440238387037],
  [0.08826815878011, 0.00460783523678],
  [0.088128492123423, 0.006772656498875],
  [0.087935740158418, 0.008933398165942],
  [0.08769001899167, 0.011088758687994],
  [0.087391476636423, 0.013237439756448],
  [0.087040292923427, 0.015378147086172],
  [0.086636679392621, 0.017509591195118],
  [0.086180879165703, 0.019630488181053],
  [0.085673166799686, 0.02173956049494],
  [0.085113848121515, 0.023835537710479],
  [0.084503260043847, 0.025917157289369],
  [0.08384177036211, 0.027983165341813],
  [0.083129777532952, 0.030032317381813],
  [0.08236771043423, 0.032063379076803],
  [0.081556028106671, 0.034075126991164],
  [0.080695219477356, 0.036066349323177],
  [0.079785803065216, 0.038035846634965],
  [0.078828326668693, 0.039982432574992],
  [0.077823367035766, 0.041904934592675],
  [0.07677152951654, 0.043802194644686],
  [0.075673447698606, 0.045673069892513],
  [0.07452978302539, 0.047516433390863],
  [0.073341224397728, 0.049331174766491],
  [0.072108487758894, 0.051116200887052],
  [0.070832315663343, 0.052870436519557],
  [0.069513476829429, 0.054592824978055],
  [0.068152765676348, 0.056282328760143],
  [0.06675100184562, 0.057937930171918],
  [0.065309029707361, 0.059558631940996],
  [0.063827717851668, 0.061143457817234],
  [0.062307958565413, 0.062691453160784],
  [0.060750667294763, 0.064201685517134],
  [0.059156782093749, 0.065673245178784],
  [0.057527263059216, 0.06710524573322],
  [0.055863091752499, 0.068496824596852],
  [0.054165270608165, 0.069847143534609],
  [0.052434822330188, 0.071155389164853],
  [0.050672789275903, 0.072420773449336],
  [0.048880232828135, 0.073642534167879],
  [0.047058232755862, 0.074819935377512],
  [0.045207886563797, 0.075952267855771],
  [0.043330308831298, 0.077038849527912],
  [0.041426630540984, 0.078079025877766],
  [0.039497998397473, 0.079072170341994],
  [0.037545574136653, 0.080017684687506],
  [0.035570533825892, 0.080914999371817],
  [0.033574067155622, 0.081763573886112],
  [0.031557376722714, 0.082562897080836],
  [0.029521677306074, 0.083312487473584],
  [0.027468195134911, 0.084011893539132],
  [0.025398167150101, 0.084660693981419],
  [0.023312840259098, 0.08525849798732],
  [0.021213470584847, 0.085804945462053],
  [0.019101322709138, 0.086299707246093],
  [0.016977668910873, 0.086742485313442],
  [0.014843788399692, 0.087133012951149],
  [0.012700966545425, 0.087471054919968],
  [0.01055049410383, 0.087756407596056],
  [0.008393666439096, 0.087988899093631],
  [0.006231782743558, 0.08816838936851],
  [0.004066145255116, 0.088294770302461],
  [0.001898058472816, 0.088367965768336]
], K3 = [
  [0.032274858518097, 13202404176e-15],
  [0.032274642494505, 118821372483e-15],
  [0.032274080835421, 224439068308e-15],
  [0.03227317354686, 330054360572e-15],
  [0.032271920638538, 435666118218e-15],
  [0.032270322123873, 541273210231e-15],
  [0.032268378019984, 646874505642e-15],
  [0.032266088347691, 752468873546e-15],
  [0.032263453131514, 858055183114e-15],
  [0.032260472399674, 9636323036e-13],
  [0.032257146184092, 0.001069199104358],
  [0.03225347452039, 0.001174754454853],
  [0.032249457447888, 0.001280297224671],
  [0.032245095009606, 0.001385826283535],
  [0.032240387252262, 0.001491340501313],
  [0.032235334226272, 0.001596838748031],
  [0.03222993598575, 0.00170231989389],
  [0.032224192588507, 0.001807782809271],
  [0.03221810409605, 0.001913226364749],
  [0.032211670573582, 0.002018649431111],
  [0.03220489209, 0.002124050879359],
  [0.032197768717898, 0.002229429580728],
  [0.03219030053356, 0.002334784406698],
  [0.032182487616965, 0.002440114229003],
  [0.032174330051782, 0.002545417919644],
  [0.032165827925374, 0.002650694350905],
  [0.03215698132879, 0.002755942395358],
  [0.032147790356771, 0.002861160925883],
  [0.032138255107744, 0.002966348815672],
  [0.032128375683825, 0.00307150493825],
  [0.032118152190814, 0.003176628167476],
  [0.032107584738196, 0.003281717377568],
  [0.032096673439141, 0.003386771443102],
  [0.0320854184105, 0.003491789239036],
  [0.032073819772804, 0.003596769640711],
  [0.032061877650267, 0.003701711523874],
  [0.032049592170778, 0.00380661376468],
  [0.032036963465906, 0.003911475239711],
  [0.032023991670893, 0.004016294825985],
  [0.032010676924657, 0.004121071400967],
  [0.031997019369789, 0.004225803842586],
  [0.031983019152549, 0.004330491029241],
  [0.031968676422869, 0.004435131839816],
  [0.031953991334348, 0.004539725153692],
  [0.031938964044252, 0.004644269850758],
  [0.03192359471351, 0.004748764811426],
  [0.031907883506716, 0.004853208916638],
  [0.031891830592124, 0.004957601047881],
  [0.031875436141648, 0.0050619400872],
  [0.031858700330859, 0.005166224917208],
  [0.031841623338985, 0.005270454421097],
  [0.031824205348907, 0.005374627482653],
  [0.031806446547156, 0.005478742986267],
  [0.031788347123916, 0.005582799816945],
  [0.031769907273017, 0.005686796860323],
  [0.031751127191935, 0.005790733002674],
  [0.031732007081789, 0.005894607130928],
  [0.03171254714734, 0.005998418132675],
  [0.031692747596989, 0.006102164896182],
  [0.031672608642773, 0.006205846310406],
  [0.031652130500364, 0.006309461265002],
  [0.031631313389067, 0.006413008650337],
  [0.031610157531816, 0.006516487357501],
  [0.031588663155172, 0.006619896278321],
  [0.031566830489325, 0.00672323430537],
  [0.031544659768083, 0.006826500331981],
  [0.031522151228878, 0.006929693252258],
  [0.031499305112758, 0.007032811961088],
  [0.031476121664387, 0.007135855354151],
  [0.03145260113204, 0.007238822327937],
  [0.031428743767604, 0.007341711779751],
  [0.031404549826572, 0.00744452260773],
  [0.031380019568042, 0.007547253710853],
  [0.031355153254712, 0.007649903988952],
  [0.031329951152882, 0.007752472342725],
  [0.031304413532445, 0.007854957673748],
  [0.031278540666888, 0.007957358884484],
  [0.03125233283329, 0.0080596748783],
  [0.031225790312316, 0.008161904559473],
  [0.031198913388214, 0.008264046833205],
  [0.031171702348814, 0.008366100605636],
  [0.031144157485525, 0.008468064783849],
  [0.031116279093331, 0.008569938275893],
  [0.031088067470786, 0.008671719990782],
  [0.031059522920014, 0.008773408838517],
  [0.031030645746705, 0.008875003730092],
  [0.03100143626011, 0.008976503577507],
  [0.030971894773039, 0.00907790729378],
  [0.030942021601857, 0.009179213792959],
  [0.030911817066483, 0.009280421990133],
  [0.030881281490382, 0.009381530801444],
  [0.030850415200566, 0.009482539144097],
  [0.030819218527589, 0.009583445936373],
  [0.030787691805541, 0.009684250097643],
  [0.030755835372048, 0.009784950548375],
  [0.030723649568268, 0.009885546210147],
  [0.030691134738883, 0.009986036005661],
  [0.030658291232103, 0.010086418858753],
  [0.030625119399655, 0.010186693694402],
  [0.030591619596781, 0.010286859438745],
  [0.030557792182239, 0.010386915019088],
  [0.030523637518292, 0.010486859363916],
  [0.03048915597071, 0.010586691402906],
  [0.030454347908763, 0.010686410066936],
  [0.030419213705216, 0.010786014288099],
  [0.030383753736329, 0.010885502999714],
  [0.030347968381849, 0.010984875136338],
  [0.03031185802501, 0.011084129633775],
  [0.030275423052523, 0.011183265429088],
  [0.030238663854579, 0.011282281460612],
  [0.030201580824838, 0.011381176667967],
  [0.03016417436043, 0.011479949992062],
  [0.030126444861948, 0.011578600375117],
  [0.030088392733446, 0.011677126760663],
  [0.03005001838243, 0.011775528093563],
  [0.030011322219859, 0.011873803320018],
  [0.029972304660138, 0.011971951387578],
  [0.029932966121114, 0.012069971245157],
  [0.02989330702407, 0.012167861843041],
  [0.029853327793724, 0.012265622132901],
  [0.029813028858222, 0.012363251067801],
  [0.029772410649132, 0.012460747602215],
  [0.029731473601443, 0.012558110692033],
  [0.029690218153558, 0.012655339294575],
  [0.029648644747289, 0.0127524323686],
  [0.029606753827855, 0.01284938887432],
  [0.029564545843872, 0.012946207773407],
  [0.029522021247356, 0.013042888029011],
  [0.02947918049371, 0.013139428605762],
  [0.029436024041725, 0.013235828469789],
  [0.02939255235357, 0.013332086588727],
  [0.029348765894794, 0.013428201931728],
  [0.029304665134313, 0.013524173469475],
  [0.029260250544412, 0.013620000174189],
  [0.029215522600735, 0.013715681019643],
  [0.029170481782283, 0.013811214981173],
  [0.029125128571406, 0.013906601035686],
  [0.029079463453801, 0.014001838161674],
  [0.029033486918505, 0.014096925339225],
  [0.028987199457889, 0.014191861550031],
  [0.028940601567655, 0.014286645777401],
  [0.028893693746829, 0.014381277006273],
  [0.028846476497755, 0.014475754223221],
  [0.028798950326094, 0.014570076416472],
  [0.028751115740811, 0.01466424257591],
  [0.028702973254178, 0.014758251693091],
  [0.02865452338176, 0.014852102761253],
  [0.028605766642418, 0.014945794775326],
  [0.028556703558297, 0.015039326731945],
  [0.028507334654823, 0.015132697629457],
  [0.028457660460698, 0.015225906467935],
  [0.028407681507891, 0.015318952249187],
  [0.028357398331639, 0.015411833976768],
  [0.028306811470432, 0.015504550655988],
  [0.028255921466016, 0.015597101293927],
  [0.028204728863381, 0.015689484899442],
  [0.02815323421076, 0.015781700483179],
  [0.028101438059619, 0.015873747057582],
  [0.028049340964652, 0.015965623636907],
  [0.027996943483779, 0.016057329237229],
  [0.027944246178133, 0.016148862876456],
  [0.027891249612061, 0.016240223574335],
  [0.027837954353113, 0.016331410352467],
  [0.027784360972039, 0.016422422234315],
  [0.02773047004278, 0.016513258245214],
  [0.027676282142466, 0.016603917412384],
  [0.027621797851405, 0.016694398764938],
  [0.02756701775308, 0.016784701333894],
  [0.027511942434143, 0.016874824152183],
  [0.027456572484404, 0.016964766254662],
  [0.027400908496833, 0.017054526678124],
  [0.027344951067546, 0.017144104461307],
  [0.027288700795801, 0.017233498644904],
  [0.027232158283994, 0.017322708271577],
  [0.027175324137651, 0.01741173238596],
  [0.027118198965418, 0.017500570034678],
  [0.02706078337906, 0.017589220266351],
  [0.027003077993454, 0.017677682131607],
  [0.026945083426576, 0.017765954683088],
  [0.026886800299502, 0.017854036975468],
  [0.026828229236397, 0.017941928065456],
  [0.026769370864511, 0.018029627011808],
  [0.02671022581417, 0.01811713287534],
  [0.026650794718768, 0.018204444718934],
  [0.026591078214767, 0.018291561607551],
  [0.02653107694168, 0.018378482608238],
  [0.026470791542075, 0.018465206790142],
  [0.026410222661558, 0.018551733224515],
  [0.026349370948775, 0.01863806098473],
  [0.026288237055398, 0.018724189146286],
  [0.026226821636121, 0.018810116786819],
  [0.026165125348656, 0.018895842986112],
  [0.026103148853718, 0.018981366826109],
  [0.026040892815028, 0.019066687390916],
  [0.025978357899296, 0.019151803766819],
  [0.025915544776223, 0.01923671504229],
  [0.025852454118485, 0.019321420307998],
  [0.025789086601733, 0.019405918656817],
  [0.025725442904582, 0.019490209183837],
  [0.025661523708606, 0.019574290986376],
  [0.025597329698327, 0.019658163163984],
  [0.025532861561211, 0.019741824818458],
  [0.025468119987662, 0.019825275053848],
  [0.025403105671008, 0.01990851297647],
  [0.025337819307501, 0.019991537694913],
  [0.025272261596305, 0.020074348320047],
  [0.025206433239491, 0.020156943965039],
  [0.025140334942028, 0.020239323745355],
  [0.025073967411776, 0.020321486778774],
  [0.025007331359476, 0.020403432185395],
  [0.024940427498748, 0.02048515908765],
  [0.024873256546079, 0.020566666610309],
  [0.024805819220816, 0.020647953880491],
  [0.024738116245157, 0.020729020027676],
  [0.024670148344147, 0.020809864183709],
  [0.024601916245669, 0.020890485482816],
  [0.024533420680433, 0.020970883061607],
  [0.024464662381971, 0.021051056059087],
  [0.02439564208663, 0.02113100361667],
  [0.024326360533561, 0.021210724878181],
  [0.024256818464715, 0.021290218989868],
  [0.02418701662483, 0.021369485100415],
  [0.02411695576143, 0.021448522360944],
  [0.024046636624808, 0.02152732992503],
  [0.023976059968027, 0.021605906948708],
  [0.023905226546906, 0.02168425259048],
  [0.023834137120014, 0.021762366011328],
  [0.023762792448662, 0.02184024637472],
  [0.023691193296893, 0.02191789284662],
  [0.023619340431478, 0.021995304595495],
  [0.023547234621902, 0.02207248079233],
  [0.023474876640361, 0.022149420610628],
  [0.023402267261751, 0.022226123226426],
  [0.023329407263659, 0.0223025878183],
  [0.023256297426359, 0.022378813567377],
  [0.023182938532797, 0.022454799657339],
  [0.023109331368588, 0.022530545274437],
  [0.023035476722006, 0.022606049607496],
  [0.022961375383975, 0.022681311847926],
  [0.022887028148061, 0.022756331189727],
  [0.022812435810462, 0.022831106829504],
  [0.022737599170003, 0.022905637966469],
  [0.022662519028125, 0.022979923802453],
  [0.022587196188874, 0.023053963541915],
  [0.022511631458899, 0.02312775639195],
  [0.022435825647437, 0.023201301562294],
  [0.022359779566306, 0.023274598265338],
  [0.0222834940299, 0.023347645716133],
  [0.022206969855176, 0.0234204431324],
  [0.022130207861645, 0.023492989734537],
  [0.022053208871367, 0.023565284745628],
  [0.02197597370894, 0.023637327391451],
  [0.021898503201489, 0.023709116900488],
  [0.021820798178663, 0.023780652503931],
  [0.021742859472618, 0.023851933435691],
  [0.021664687918017, 0.023922958932406],
  [0.021586284352013, 0.023993728233451],
  [0.021507649614247, 0.024064240580942],
  [0.021428784546832, 0.02413449521975],
  [0.02134968999435, 0.024204491397504],
  [0.02127036680384, 0.0242742283646],
  [0.021190815824791, 0.024343705374213],
  [0.021111037909128, 0.024412921682298],
  [0.02103103391121, 0.024481876547605],
  [0.020950804687815, 0.024550569231683],
  [0.020870351098134, 0.024618998998889],
  [0.020789674003759, 0.024687165116394],
  [0.020708774268678, 0.024755066854194],
  [0.020627652759262, 0.024822703485116],
  [0.020546310344257, 0.024890074284826],
  [0.020464747894775, 0.024957178531837],
  [0.020382966284284, 0.025024015507516],
  [0.0203009663886, 0.025090584496093],
  [0.020218749085876, 0.025156884784668],
  [0.020136315256592, 0.025222915663218],
  [0.020053665783549, 0.025288676424605],
  [0.019970801551857, 0.025354166364584],
  [0.019887723448925, 0.025419384781811],
  [0.019804432364452, 0.025484330977848],
  [0.019720929190419, 0.025549004257175],
  [0.019637214821078, 0.025613403927192],
  [0.019553290152943, 0.02567752929823],
  [0.019469156084779, 0.025741379683559],
  [0.019384813517595, 0.025804954399392],
  [0.019300263354632, 0.025868252764895],
  [0.019215506501354, 0.025931274102193],
  [0.019130543865439, 0.025994017736379],
  [0.019045376356769, 0.026056482995518],
  [0.018960004887419, 0.026118669210657],
  [0.018874430371648, 0.026180575715833],
  [0.018788653725892, 0.026242201848076],
  [0.01870267586875, 0.026303546947421],
  [0.018616497720974, 0.026364610356909],
  [0.018530120205464, 0.026425391422602],
  [0.018443544247254, 0.026485889493583],
  [0.018356770773502, 0.026546103921965],
  [0.018269800713483, 0.026606034062902],
  [0.018182634998576, 0.026665679274589],
  [0.018095274562256, 0.026725038918274],
  [0.018007720340083, 0.026784112358263],
  [0.017919973269692, 0.026842898961926],
  [0.017832034290785, 0.026901398099707],
  [0.017743904345116, 0.026959609145127],
  [0.017655584376488, 0.027017531474792],
  [0.017567075330734, 0.027075164468401],
  [0.017478378155718, 0.02713250750875],
  [0.017389493801313, 0.027189559981742],
  [0.017300423219401, 0.027246321276391],
  [0.017211167363854, 0.027302790784828],
  [0.017121727190533, 0.02735896790231],
  [0.017032103657269, 0.027414852027226],
  [0.016942297723858, 0.027470442561102],
  [0.01685231035205, 0.027525738908608],
  [0.016762142505537, 0.027580740477564],
  [0.016671795149944, 0.027635446678948],
  [0.016581269252819, 0.0276898569269],
  [0.016490565783622, 0.02774397063873],
  [0.016399685713714, 0.027797787234924],
  [0.016308630016347, 0.027851306139149],
  [0.016217399666655, 0.02790452677826],
  [0.016125995641641, 0.027957448582309],
  [0.01603441892017, 0.028010070984544],
  [0.015942670482954, 0.028062393421421],
  [0.015850751312545, 0.02811441533261],
  [0.015758662393324, 0.028166136160998],
  [0.015666404711489, 0.028217555352697],
  [0.015573979255046, 0.028268672357047],
  [0.015481387013797, 0.028319486626627],
  [0.015388628979331, 0.028369997617257],
  [0.015295706145012, 0.028420204788004],
  [0.015202619505968, 0.028470107601191],
  [0.015109370059084, 0.028519705522399],
  [0.015015958802984, 0.028568998020472],
  [0.01492238673803, 0.028617984567529],
  [0.014828654866302, 0.028666664638963],
  [0.014734764191593, 0.028715037713449],
  [0.014640715719398, 0.028763103272951],
  [0.0145465104569, 0.028810860802724],
  [0.014452149412962, 0.028858309791325],
  [0.014357633598114, 0.028905449730613],
  [0.014262964024545, 0.028952280115756],
  [0.01416814170609, 0.02899880044524],
  [0.01407316765822, 0.029045010220868],
  [0.01397804289803, 0.029090908947771],
  [0.013882768444231, 0.029136496134411],
  [0.013787345317136, 0.029181771292585],
  [0.013691774538648, 0.029226733937433],
  [0.013596057132255, 0.029271383587441],
  [0.013500194123014, 0.029315719764447],
  [0.013404186537539, 0.029359741993647],
  [0.013308035403995, 0.029403449803598],
  [0.013211741752084, 0.029446842726223],
  [0.013115306613032, 0.02948992029682],
  [0.013018731019584, 0.029532682054063],
  [0.012922016005985, 0.029575127540008],
  [0.012825162607977, 0.029617256300097],
  [0.012728171862781, 0.029659067883165],
  [0.012631044809089, 0.029700561841444],
  [0.012533782487056, 0.029741737730567],
  [0.012436385938281, 0.029782595109573],
  [0.012338856205805, 0.029823133540913],
  [0.012241194334091, 0.029863352590452],
  [0.012143401369021, 0.029903251827477],
  [0.012045478357878, 0.029942830824699],
  [0.011947426349339, 0.029982089158259],
  [0.011849246393462, 0.030021026407731],
  [0.011750939541676, 0.030059642156129],
  [0.011652506846768, 0.030097935989909],
  [0.011553949362874, 0.030135907498976],
  [0.011455268145464, 0.030173556276684],
  [0.011356464251335, 0.030210881919845],
  [0.011257538738598, 0.030247884028732],
  [0.011158492666665, 0.030284562207083],
  [0.01105932709624, 0.030320916062102],
  [0.010960043089307, 0.03035694520447],
  [0.010860641709118, 0.030392649248343],
  [0.010761124020182, 0.030428027811361],
  [0.010661491088253, 0.030463080514646],
  [0.010561743980319, 0.030497806982812],
  [0.010461883764593, 0.030532206843968],
  [0.010361911510496, 0.030566279729717],
  [0.010261828288652, 0.030600025275167],
  [0.010161635170872, 0.030633443118931],
  [0.010061333230142, 0.030666532903129],
  [0.009960923540617, 0.030699294273397],
  [0.009860407177603, 0.030731726878888],
  [0.00975978521755, 0.030763830372273],
  [0.009659058738038, 0.03079560440975],
  [0.009558228817767, 0.030827048651045],
  [0.009457296536545, 0.030858162759415],
  [0.009356262975275, 0.030888946401653],
  [0.009255129215945, 0.030919399248091],
  [0.009153896341616, 0.030949520972603],
  [0.009052565436412, 0.030979311252611],
  [0.008951137585505, 0.031008769769084],
  [0.008849613875105, 0.031037896206544],
  [0.008747995392451, 0.031066690253072],
  [0.008646283225794, 0.031095151600306],
  [0.00854447846439, 0.031123279943448],
  [0.008442582198486, 0.031151074981266],
  [0.00834059551931, 0.031178536416098],
  [0.008238519519057, 0.031205663953853],
  [0.008136355290878, 0.031232457304017],
  [0.008034103928871, 0.031258916179656],
  [0.007931766528065, 0.031285040297416],
  [0.007829344184412, 0.031310829377528],
  [0.007726837994772, 0.031336283143813],
  [0.007624249056906, 0.03136140132368],
  [0.007521578469457, 0.031386183648135],
  [0.007418827331946, 0.031410629851778],
  [0.007315996744755, 0.031434739672811],
  [0.007213087809115, 0.031458512853036],
  [0.007110101627101, 0.031481949137863],
  [0.00700703930161, 0.031505048276306],
  [0.006903901936357, 0.031527810020993],
  [0.006800690635862, 0.031550234128164],
  [0.006697406505433, 0.031572320357675],
  [0.006594050651161, 0.031594068473],
  [0.006490624179905, 0.031615478241233],
  [0.006387128199278, 0.031636549433095],
  [0.006283563817639, 0.031657281822929],
  [0.00617993214408, 0.031677675188707],
  [0.006076234288412, 0.031697729312034],
  [0.005972471361157, 0.031717443978146],
  [0.005868644473532, 0.031736818975914],
  [0.00576475473744, 0.031755854097848],
  [0.005660803265456, 0.031774549140098],
  [0.005556791170816, 0.031792903902453],
  [0.005452719567407, 0.03181091818835],
  [0.005348589569753, 0.031828591804869],
  [0.005244402293001, 0.031845924562742],
  [0.005140158852914, 0.031862916276347],
  [0.005035860365855, 0.031879566763717],
  [0.004931507948778, 0.031895875846539],
  [0.004827102719212, 0.031911843350155],
  [0.004722645795254, 0.031927469103567],
  [0.004618138295554, 0.031942752939435],
  [0.004513581339303, 0.031957694694082],
  [0.004408976046222, 0.031972294207493],
  [0.004304323536549, 0.03198655132332],
  [0.00419962493103, 0.032000465888879],
  [0.004094881350902, 0.032014037755158],
  [0.003990093917884, 0.032027266776813],
  [0.003885263754166, 0.03204015281217],
  [0.003780391982394, 0.032052695723232],
  [0.003675479725661, 0.032064895375674],
  [0.003570528107494, 0.032076751638847],
  [0.003465538251839, 0.03208826438578],
  [0.003360511283053, 0.032099433493181],
  [0.003255448325892, 0.032110258841438],
  [0.003150350505494, 0.032120740314619],
  [0.003045218947373, 0.032130877800478],
  [0.002940054777404, 0.032140671190449],
  [0.00283485912181, 0.032150120379653],
  [0.002729633107153, 0.032159225266897],
  [0.002624377860318, 0.032167985754674],
  [0.002519094508504, 0.032176401749168],
  [0.002413784179212, 0.03218447316025],
  [0.002308448000231, 0.032192199901481],
  [0.002203087099626, 0.032199581890114],
  [0.002097702605728, 0.032206619047093],
  [0.001992295647121, 0.032213311297057],
  [0.001886867352628, 0.032219658568338],
  [0.001781418851302, 0.03222566079296],
  [0.00167595127241, 0.032231317906644],
  [0.001570465745428, 0.032236629848809],
  [0.001464963400018, 0.032241596562566],
  [0.001359445366028, 0.032246217994727],
  [0.00125391277347, 0.032250494095799],
  [0.001148366752513, 0.03225442481999],
  [0.001042808433471, 0.032258010125204],
  [937238946789e-15, 0.032261249973045],
  [83165942303e-14, 0.032264144328817],
  [726070992868e-15, 0.032266693161525],
  [620474787068e-15, 0.032268896443871],
  [514871936481e-15, 0.032270754152261],
  [40926357203e-14, 0.032272266266801],
  [303650824695e-15, 0.032273432771295],
  [198034825504e-15, 0.032274253653254],
  [92416705518e-15, 0.032274728903884]
], X3 = [
  [0.091286604111815, 298735779793e-15],
  [0.091247502481454, 0.002688238127538],
  [0.091145864370807, 0.005075898091152],
  [0.090981759437558, 0.00746007928776],
  [0.09075530015103, 0.009839147718664],
  [0.090466641715108, 0.012211472889198],
  [0.090115981961863, 0.014575428926191],
  [0.089703561215976, 0.016929395692256],
  [0.089229662130024, 0.019271759896156],
  [0.088694609490769, 0.02160091619847],
  [0.088098769996564, 0.02391526831181],
  [0.087442552006035, 0.026213230094844],
  [0.086726405258214, 0.028493226639351],
  [0.085950820564309, 0.030753695349588],
  [0.085116329471329, 0.032993087013213],
  [0.084223503897785, 0.035209866863042],
  [0.083272955741727, 0.037402515628894],
  [0.082265336461381, 0.039569530578832],
  [0.08120133662867, 0.041709426549053],
  [0.08008168545593, 0.043820736961749],
  [0.078907150296148, 0.045902014830227],
  [0.077678536117054, 0.047951833750597],
  [0.076396684949434, 0.049968788879362],
  [0.07506247531005, 0.051951497896226],
  [0.073676821599542, 0.053898601951466],
  [0.072240673475749, 0.055808766597225],
  [0.070755015202858, 0.057680682702068],
  [0.06922086497684, 0.059513067348201],
  [0.067639274227625, 0.061304664710718],
  [0.066011326898512, 0.063054246918278],
  [0.064338138703282, 0.06476061489463],
  [0.062620856361546, 0.066422599180399],
  [0.060860656812842, 0.068039060734572],
  [0.059058746410016, 0.069608891715145],
  [0.05721636009245, 0.071131016238378],
  [0.055334760539699, 0.072604391116154],
  [0.053415237306106, 0.07402800657093],
  [0.051459105937014, 0.075400886927784],
  [0.049467707067153, 0.076722091283096],
  [0.047442405501835, 0.077990714149396],
  [0.045384589281588, 0.079205886075941],
  [0.043295668730857, 0.080366774244592],
  [0.041177075491445, 0.081472583040586],
  [0.039030261541332, 0.08252255459781],
  [0.036856698199564, 0.083515969318206],
  [0.034657875117883, 0.084452146364948],
  [0.032435299259796, 0.085330444129049],
  [0.030190493867775, 0.086150260669096],
  [0.027924997419306, 0.086911034123781],
  [0.025640362572491, 0.087612243096981],
  [0.023338155101933, 0.088253407015092],
  [0.021019952825636, 0.08883408645639],
  [0.018687344523641, 0.089353883452193],
  [0.016341928849164, 0.089812441759604],
  [0.013985313232951, 0.090209447105664],
  [0.011619112781631, 0.09054462740274],
  [0.009244949170797, 0.090817752935],
  [0.006864449533597, 0.091028636515846],
  [0.004479245345574, 0.091177133616206],
  [0.002090971306534, 0.091263142463585]
];
function Lg(r) {
  switch (this.length = r, r) {
    case 64:
      this.roots = Nf(64);
      break;
    case 512:
      this.roots = Gf(512);
      break;
    case 60:
      this.roots = Nf(60);
      break;
    case 480:
      this.roots = Gf(480);
      break;
    default:
      throw new Error("unexpected FFT length: " + r);
  }
  this.rev = new Array(r);
  for (let e = 0; e < r; e++)
    this.rev[e] = new Float32Array(2);
  this.a = new Float32Array(2), this.b = new Float32Array(2), this.c = new Float32Array(2), this.d = new Float32Array(2), this.e1 = new Float32Array(2), this.e2 = new Float32Array(2);
}
function Nf(r) {
  let e = 2 * Math.PI / r, t = Math.cos(e), i = Math.sin(e), s = new Array(r), n = 0;
  for (; n < r; n++)
    s[n] = new Float32Array(2);
  s[0][0] = 1, s[0][1] = 0;
  let a = 0;
  for (n = 1; n < r; n++)
    s[n][0] = s[n - 1][0] * t + a * i, a = a * t - s[n - 1][0] * i, s[n][1] = -a;
  return s;
}
function Gf(r) {
  let e = 2 * Math.PI / r, t = Math.cos(e), i = Math.sin(e), s = new Array(r), n = 0;
  for (; n < r; n++)
    s[n] = new Float32Array(3);
  for (s[0][0] = 1, s[0][1] = 0, s[0][2] = 0, n = 1; n < r; n++)
    s[n][0] = s[n - 1][0] * t + s[n - 1][2] * i, s[n][2] = s[n - 1][2] * t - s[n - 1][0] * i, s[n][1] = -s[n][2];
  return s;
}
Lg.prototype.process = function(r, e) {
  let t = this.length, i = e ? 2 : 1, s = e ? t : 1, n = this.rev, a = this.roots, o = 0, c = 0;
  for (; c < t; c++) {
    n[c][0] = r[o][0], n[c][1] = r[o][1];
    let m = t >>> 1;
    for (; o >= m && m > 0; )
      o -= m, m >>= 1;
    o += m;
  }
  let l = this.a, d = this.b, h = this.c, u = this.d, f = this.e1, p = this.e2;
  for (c = 0; c < t; c++)
    r[c][0] = n[c][0], r[c][1] = n[c][1];
  for (c = 0; c < t; c += 4)
    l[0] = r[c][0] + r[c + 1][0], l[1] = r[c][1] + r[c + 1][1], d[0] = r[c + 2][0] + r[c + 3][0], d[1] = r[c + 2][1] + r[c + 3][1], h[0] = r[c][0] - r[c + 1][0], h[1] = r[c][1] - r[c + 1][1], u[0] = r[c + 2][0] - r[c + 3][0], u[1] = r[c + 2][1] - r[c + 3][1], r[c][0] = l[0] + d[0], r[c][1] = l[1] + d[1], r[c + 2][0] = l[0] - d[0], r[c + 2][1] = l[1] - d[1], f[0] = h[0] - u[1], f[1] = h[1] + u[0], p[0] = h[0] + u[1], p[1] = h[1] - u[0], e ? (r[c + 1][0] = p[0], r[c + 1][1] = p[1], r[c + 3][0] = f[0], r[c + 3][1] = f[1]) : (r[c + 1][0] = f[0], r[c + 1][1] = f[1], r[c + 3][0] = p[0], r[c + 3][1] = p[1]);
  for (c = 4; c < t; c <<= 1) {
    let m = c << 1, g = t / m;
    for (let x = 0; x < t; x += m)
      for (let _ = 0; _ < c; _++) {
        let v = _ * g, E = a[v][0], b = a[v][i], A = r[c + x + _][0] * E - r[c + x + _][1] * b, C = r[c + x + _][0] * b + r[c + x + _][1] * E;
        r[c + x + _][0] = (r[x + _][0] - A) * s, r[c + x + _][1] = (r[x + _][1] - C) * s, r[x + _][0] = (r[x + _][0] + A) * s, r[x + _][1] = (r[x + _][1] + C) * s;
      }
  }
};
function Cc(r) {
  switch (this.N = r, this.N2 = r >>> 1, this.N4 = r >>> 2, this.N8 = r >>> 3, r) {
    case 2048:
      this.sincos = Z3;
      break;
    case 256:
      this.sincos = $3;
      break;
    case 1920:
      this.sincos = K3;
      break;
    case 240:
      this.sincos = X3;
      break;
    default:
      throw new Error("unsupported MDCT length: " + r);
  }
  this.fft = new Lg(this.N4), this.buf = new Array(this.N4);
  for (let e = 0; e < this.N4; e++)
    this.buf[e] = new Float32Array(2);
  this.tmp = new Float32Array(2);
}
Cc.prototype.process = function(r, e, t, i) {
  let s = this.N2, n = this.N4, a = this.N8, o = this.buf, c = this.tmp, l = this.sincos, d = this.fft, h;
  for (h = 0; h < n; h++)
    o[h][1] = r[e + 2 * h] * l[h][0] + r[e + s - 1 - 2 * h] * l[h][1], o[h][0] = r[e + s - 1 - 2 * h] * l[h][0] - r[e + 2 * h] * l[h][1];
  for (d.process(o, !1), h = 0; h < n; h++)
    c[0] = o[h][0], c[1] = o[h][1], o[h][1] = c[1] * l[h][0] + c[0] * l[h][1], o[h][0] = c[0] * l[h][0] - c[1] * l[h][1];
  for (h = 0; h < a; h += 2)
    t[i + 2 * h] = o[a + h][1], t[i + 2 + 2 * h] = o[a + 1 + h][1], t[i + 1 + 2 * h] = -o[a - 1 - h][0], t[i + 3 + 2 * h] = -o[a - 2 - h][0], t[i + n + 2 * h] = o[h][0], t[i + n + 2 + 2 * h] = o[1 + h][0], t[i + n + 1 + 2 * h] = -o[n - 1 - h][1], t[i + n + 3 + 2 * h] = -o[n - 2 - h][1], t[i + s + 2 * h] = o[a + h][0], t[i + s + 2 + 2 * h] = o[a + 1 + h][0], t[i + s + 1 + 2 * h] = -o[a - 1 - h][1], t[i + s + 3 + 2 * h] = -o[a - 2 - h][1], t[i + s + n + 2 * h] = -o[h][1], t[i + s + n + 2 + 2 * h] = -o[1 + h][1], t[i + s + n + 1 + 2 * h] = o[n - 1 - h][0], t[i + s + n + 3 + 2 * h] = o[n - 2 - h][0];
};
function Dg(r, e) {
  if (r)
    throw new Error("WHA?? No small frames allowed.");
  this.length = 1024, this.shortLength = 128, this.mid = (this.length - this.shortLength) / 2, this.trans = this.shortLength / 2, this.mdctShort = new Cc(this.shortLength * 2), this.mdctLong = new Cc(this.length * 2), this.overlaps = new Array(e);
  for (let t = 0; t < e; t++)
    this.overlaps[t] = new Float32Array(this.length);
  this.buf = new Float32Array(2 * this.length);
}
function Pg(r) {
  let e = new Float32Array(r);
  for (let t = 0; t < r; t++)
    e[t] = Math.sin((t + 0.5) * (Math.PI / (2 * r)));
  return e;
}
function kg(r, e) {
  let t = Math.PI / e, i = new Float32Array(e), s = 0, n = new Float32Array(e), a = r * t * (r * t), o = 0;
  for (; o < e; o++) {
    let c = o * (e - o) * a, l = 1;
    for (let d = 50; d > 0; d--)
      l = l * c / (d * d) + 1;
    s += l, n[o] = s;
  }
  for (s++, o = 0; o < e; o++)
    i[o] = Math.sqrt(n[o] / s);
  return i;
}
const Y3 = Pg(1024), z3 = Pg(128), j3 = kg(4, 1024), Q3 = kg(6, 128), Uf = [Y3, j3], Vf = [z3, Q3];
Dg.prototype.process = function(r, e, t, i) {
  let s = this.overlaps[i], n = r.windowShape[1], a = r.windowShape[0], o = Uf[n], c = Vf[n], l = Uf[a], d = Vf[a], h = this.length, u = this.shortLength, f = this.mid, p = this.trans, m = this.buf, g = this.mdctLong, x = this.mdctShort, _;
  switch (r.windowSequence) {
    case ue.ONLY_LONG_SEQUENCE:
      for (g.process(e, 0, m, 0), _ = 0; _ < h; _++)
        t[_] = s[_] + m[_] * l[_];
      for (_ = 0; _ < h; _++)
        s[_] = m[h + _] * o[h - 1 - _];
      break;
    case ue.LONG_START_SEQUENCE:
      for (g.process(e, 0, m, 0), _ = 0; _ < h; _++)
        t[_] = s[_] + m[_] * l[_];
      for (_ = 0; _ < f; _++)
        s[_] = m[h + _];
      for (_ = 0; _ < u; _++)
        s[f + _] = m[h + f + _] * c[u - _ - 1];
      for (_ = 0; _ < f; _++)
        s[f + u + _] = 0;
      break;
    case ue.EIGHT_SHORT_SEQUENCE:
      for (_ = 0; _ < 8; _++)
        x.process(e, _ * u, m, 2 * _ * u);
      for (_ = 0; _ < f; _++)
        t[_] = s[_];
      for (_ = 0; _ < u; _++)
        t[f + _] = s[f + _] + m[_] * d[_], t[f + 1 * u + _] = s[f + u * 1 + _] + m[u * 1 + _] * c[u - 1 - _] + m[u * 2 + _] * c[_], t[f + 2 * u + _] = s[f + u * 2 + _] + m[u * 3 + _] * c[u - 1 - _] + m[u * 4 + _] * c[_], t[f + 3 * u + _] = s[f + u * 3 + _] + m[u * 5 + _] * c[u - 1 - _] + m[u * 6 + _] * c[_], _ < p && (t[f + 4 * u + _] = s[f + u * 4 + _] + m[u * 7 + _] * c[u - 1 - _] + m[u * 8 + _] * c[_]);
      for (_ = 0; _ < u; _++)
        _ >= p && (s[f + 4 * u + _ - h] = m[u * 7 + _] * c[u - 1 - _] + m[u * 8 + _] * c[_]), s[f + 5 * u + _ - h] = m[u * 9 + _] * c[u - 1 - _] + m[u * 10 + _] * c[_], s[f + 6 * u + _ - h] = m[u * 11 + _] * c[u - 1 - _] + m[u * 12 + _] * c[_], s[f + 7 * u + _ - h] = m[u * 13 + _] * c[u - 1 - _] + m[u * 14 + _] * c[_], s[f + 8 * u + _ - h] = m[u * 15 + _] * c[u - 1 - _];
      for (_ = 0; _ < f; _++)
        s[f + u + _] = 0;
      break;
    case ue.LONG_STOP_SEQUENCE:
      for (g.process(e, 0, m, 0), _ = 0; _ < f; _++)
        t[_] = s[_];
      for (_ = 0; _ < u; _++)
        t[f + _] = s[f + _] + m[f + _] * d[_];
      for (_ = 0; _ < f; _++)
        t[f + u + _] = s[f + u + _] + m[f + u + _];
      for (_ = 0; _ < h; _++)
        s[_] = m[h + _] * o[h - 1 - _];
      break;
  }
};
const m0 = 1, J3 = 2, $r = 4, q3 = 31, e4 = 0, t4 = 0, i4 = 1, s4 = 2, r4 = 3, n4 = 4, a4 = 5, o4 = 6, l4 = 7;
let c4 = class extends ve {
  constructor(e, t) {
    super();
    let i;
    this.demuxer = e, this.format = t, i = new Ji(), this.stream = new he(i), this.bitstream = new Ct(this.stream), this.receivedFinalBuffer = !1, this.waiting = !1, this.demuxer.on("cookie", (s) => {
      let n;
      try {
        return this.setCookie(s);
      } catch (a) {
        return n = a, this.emit("error", n);
      }
    }), this.demuxer.on("data", (s) => {
      if (i.append(s), this.waiting)
        return this.decode();
    }), this.demuxer.on("end", () => {
      if (this.receivedFinalBuffer = !0, this.waiting)
        return this.decode();
    }), this.init();
  }
  init() {
    this.format.floatingPoint = !0;
  }
  setCookie(e) {
    let t = he.fromBuffer(e), i = new Ct(t);
    if (this.config = {}, this.config.profile = i.read(5), this.config.profile === q3 && (this.config.profile = 32 + i.read(6)), this.config.sampleIndex = i.read(4), this.config.sampleIndex === 15) {
      this.config.sampleRate = i.read(24);
      for (let s = 0; s < Ra.length; s++)
        if (Ra[s] === this.config.sampleRate) {
          this.config.sampleIndex = s;
          break;
        }
    } else
      this.config.sampleRate = Ra[this.config.sampleIndex];
    switch (this.config.chanConfig = i.read(4), this.format.channelsPerFrame = this.config.chanConfig, this.config.profile) {
      case m0:
      case J3:
      case $r:
        if (i.read(1))
          throw new Error("frameLengthFlag not supported");
        if (this.config.frameLength = 1024, i.read(1) && i.advance(14), i.read(1) && (this.config.profile > 16 && (this.config.sectionDataResilience = i.read(1), this.config.scalefactorResilience = i.read(1), this.config.spectralDataResilience = i.read(1)), i.advance(1)), this.config.chanConfig === e4)
          throw i.advance(4), new Error("PCE unimplemented");
        break;
      default:
        throw new Error("AAC profile " + this.config.profile + " not supported.");
    }
    this.filter_bank = new Dg(!1, this.config.chanConfig);
  }
  // The main decoding function.
  readChunk() {
    let e = this.bitstream;
    e.peek(12) === 4095 && Co.readHeader(e), this.cces = [];
    let t = [], i = this.config, s = i.frameLength, n = null;
    for (; (n = e.read(3)) !== l4; ) {
      let d = e.read(4);
      switch (n) {
        case t4:
        case r4:
          {
            let h = new ue(this.config);
            h.id = d, t.push(h), h.decode(e, i, !1);
          }
          break;
        case i4:
          {
            let h = new Ia(this.config);
            h.id = d, t.push(h), h.decode(e, i);
          }
          break;
        case s4:
          {
            let h = new Tt(this.config);
            this.cces.push(h), h.decode(e, i);
          }
          break;
        case n4:
          {
            let h = e.read(1), u = e.read(8);
            u === 255 && (u += e.read(8)), h && e.align(), e.advance(u * 8);
          }
          break;
        case a4:
          throw new Error("TODO: PCE_ELEMENT");
        case o4:
          d === 15 && (d += e.read(8) - 1), e.advance(d * 8);
          break;
        default:
          throw new Error("Unknown element");
      }
    }
    e.align(), this.process(t);
    let a = this.data, o = a.length, c = new Float32Array(s * o), l = 0;
    for (let d = 0; d < s; d++)
      for (let h = 0; h < o; h++)
        c[l++] = a[h][d] / 32768;
    return c;
  }
  decode() {
    let e, t, i;
    this.waiting = !this.receivedFinalBuffer, t = this.bitstream.offset();
    try {
      i = this.readChunk();
    } catch (s) {
      if (e = s, !(e instanceof Mn))
        return this.emit("error", e), !1;
    }
    return i ? (this.emit("data", i), this.receivedFinalBuffer && this.emit("end"), !0) : (this.receivedFinalBuffer ? this.emit("end") : (this.bitstream.seek(t), this.waiting = !0), !1);
  }
  seek(e) {
    let t = this.demuxer.seek(e);
    return this.stream.seek(t.offset), t.timestamp;
  }
  process(e) {
    let t = this.config.chanConfig, i = 1, s, n = i * this.config.frameLength, a = this.data = [];
    for (s = 0; s < t; s++)
      a[s] = new Float32Array(n);
    let o = 0;
    for (s = 0; s < e.length && o < t; s++) {
      let c = e[s];
      if (c instanceof ue)
        o += this.processSingle(c, o);
      else if (c instanceof Ia)
        this.processPair(c, o), o += 2;
      else if (c instanceof Tt)
        o++;
      else
        throw new Error("Unknown element found.");
    }
  }
  processSingle(e, t) {
    let i = this.config.profile, s = e.info, n = e.data;
    if (i === m0)
      throw new Error("Main prediction unimplemented");
    if (i === $r)
      throw new Error("LTP prediction unimplemented");
    if (this.applyChannelCoupling(e, Tt.BEFORE_TNS, n, null), e.tnsPresent && e.tns.process(e, n, !1), this.applyChannelCoupling(e, Tt.AFTER_TNS, n, null), this.filter_bank.process(s, n, this.data[t], t), i === $r)
      throw new Error("LTP prediction unimplemented");
    if (this.applyChannelCoupling(e, Tt.AFTER_IMDCT, this.data[t], null), e.gainPresent)
      throw new Error("Gain control not implemented");
    if (this.sbrPresent)
      throw new Error("SBR not implemented");
    return 1;
  }
  processPair(e, t) {
    let i = this.config.profile, s = e.left, n = e.right, a = s.info, o = n.info, c = s.data, l = n.data;
    if (e.commonWindow && e.maskPresent && this.processMS(e, c, l), i === m0)
      throw new Error("Main prediction unimplemented");
    if (this.processIS(e, c, l), i === $r)
      throw new Error("LTP prediction unimplemented");
    if (this.applyChannelCoupling(e, Tt.BEFORE_TNS, c, l), s.tnsPresent && s.tns.process(s, c, !1), n.tnsPresent && n.tns.process(n, l, !1), this.applyChannelCoupling(e, Tt.AFTER_TNS, c, l), this.filter_bank.process(a, c, this.data[t], t), this.filter_bank.process(o, l, this.data[t + 1], t + 1), i === $r)
      throw new Error("LTP prediction unimplemented");
    if (this.applyChannelCoupling(e, Tt.AFTER_IMDCT, this.data[t], this.data[t + 1]), s.gainPresent)
      throw new Error("Gain control not implemented");
    if (n.gainPresent)
      throw new Error("Gain control not implemented");
    if (this.sbrPresent)
      throw new Error("SBR not implemented");
  }
  // Intensity stereo
  processIS(e, t, i) {
    let s = e.right, n = s.info, a = n.swbOffsets, o = n.groupCount, c = n.maxSFB, l = s.bandTypes, d = s.sectEnd, h = s.scaleFactors, u = 0, f = 0;
    for (let p = 0; p < o; p++) {
      for (let m = 0; m < c; ) {
        let g = d[u];
        if (l[u] === ue.INTENSITY_BT || l[u] === ue.INTENSITY_BT2)
          for (; m < g; m++, u++) {
            let x = l[u] === ue.INTENSITY_BT ? 1 : -1;
            e.maskPresent && (x *= e.ms_used[u] ? -1 : 1);
            let _ = x * h[u];
            for (let v = 0; v < n.groupLength[p]; v++) {
              let E = f + v * 128 + a[m], b = a[m + 1] - a[m];
              for (let A = 0; A < b; A++)
                i[E + A] = t[E + A] * _;
            }
          }
        else
          u += g - m, m = g;
      }
      f += n.groupLength[p] * 128;
    }
  }
  // Mid-side stereo
  processMS(e, t, i) {
    let s = e.left, n = s.info, a = n.swbOffsets, o = n.groupCount, c = n.maxSFB, l = s.bandTypes, d = e.right.bandTypes, h = 0, u = 0;
    for (let f = 0; f < o; f++) {
      for (let p = 0; p < c; p++, u++)
        if (e.ms_used[u] && l[u] < ue.NOISE_BT && d[u] < ue.NOISE_BT)
          for (let m = 0; m < n.groupLength[f]; m++) {
            let g = h + m * 128 + a[p];
            for (let x = 0; x < a[p + 1] - a[p]; x++) {
              let _ = t[g + x] - i[g + x];
              t[g + x] += i[g + x], i[g + x] = _;
            }
          }
      h += n.groupLength[f] * 128;
    }
  }
  applyChannelCoupling(e, t, i, s) {
    let n = this.cces, a = e instanceof Ia, o = t === Tt.AFTER_IMDCT ? "applyIndependentCoupling" : "applyDependentCoupling";
    for (let c = 0; c < n.length; c++) {
      let l = n[c], d = 0;
      if (l.couplingPoint === t)
        for (let h = 0; h < l.coupledCount; h++) {
          let u = l.chSelect[h];
          l.channelPair[h] === a && l.idSelect[h] === e.id ? (u !== 1 && (l[o](d, i), u && d++), u !== 2 && l[o](d++, s)) : d += 1 + (u === 3 ? 1 : 0);
        }
    }
  }
};
class d4 extends ve {
  constructor(t) {
    super();
    y(this, "TAG");
    y(this, "active", !1);
    y(this, "source", new ve());
    y(this, "calcTimeCount", 0);
    y(this, "demuxer");
    y(this, "decoder");
    y(this, "initDecoder", (t) => {
      let i = this.decoder = new c4(this.demuxer, t);
      for (this.active = !0, i.on("data", (s) => {
        this.calcTimeCount++, this.emit("data", s);
      }), i.on("error", (s) => {
        S.e(this.TAG, "onError ", (s == null ? void 0 : s.message) || (s == null ? void 0 : s.stack) || (s == null ? void 0 : s.toString())), this.emit("error", s);
      }), i.on("end", () => (S.d("------------- aac decode end"), this.active = !1, this.emit("end"))); i.decode() && this.active; )
        ;
    });
    this.TAG = S.traceTag("AACDecoderImpl", t);
  }
  decode(t) {
    var n;
    const { data: i } = t, s = new at(i);
    if (!this.demuxer) {
      let a = this.demuxer = new Co(this.source, s);
      a.on("format", this.initDecoder), a.readChunk();
      return;
    }
    (n = this.source) == null || n.emit("data", s);
  }
  destroy() {
    this.removeAllListeners(), this.decoder && (this.decoder.removeAllListeners(), this.decoder = void 0), this.demuxer && (this.demuxer.removeAllListeners(), this.demuxer = void 0), this.source && (this.source.removeAllListeners(), this.source = void 0);
  }
}
const wg = " ", h4 = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)), Wf = typeof self < "u" && self.Blob && new Blob([h4(wg)], { type: "text/javascript;charset=utf-8" });
function u4(r) {
  let e;
  try {
    if (e = Wf && (self.URL || self.webkitURL).createObjectURL(Wf), !e) throw "";
    const t = new Worker(e, {
      name: r == null ? void 0 : r.name
    });
    return t.addEventListener("error", () => {
      (self.URL || self.webkitURL).revokeObjectURL(e);
    }), t;
  } catch {
    return new Worker(
      "data:text/javascript;base64," + wg,
      {
        name: r == null ? void 0 : r.name
      }
    );
  } finally {
    e && (self.URL || self.webkitURL).revokeObjectURL(e);
  }
}
class Mg extends Rd {
  constructor(t, i) {
    const { enableAudioWorker: s, manaulGCInterval: n, traceId: a } = i;
    super(Mt.AACDecoder, t.codecType, a);
    y(this, "worker");
    y(this, "decoder");
    y(this, "onWorkerMessage", (t) => {
      let i = t.data, s = i.data;
      switch (i.msg) {
        case "data":
          this.audioDecodeEnd(s);
          break;
        case "error":
          this.decodeError(t);
          break;
      }
    });
    if (s && typeof Worker < "u")
      try {
        this.worker = new _s(new u4(), Us.DecodeAACAudio, a), this.worker.onWorkerMessage = this.onWorkerMessage, this.worker.init({ manaulGCInterval: n }, a);
      } catch (o) {
        S.e(this.TAG, "Error while initialize WCSAudioDecoder worker, fallback to inline WCSAudioDecoder", (o == null ? void 0 : o.message) || (o == null ? void 0 : o.stack) || (o == null ? void 0 : o.toString()));
      }
    if (!this.worker) {
      const o = this.decoder = new d4(a);
      o.on("data", this.audioDecodeEnd.bind(this)), o.on("error", this.decodeError);
    }
  }
  decode(t, i) {
    var o;
    const { dts: s, duration: n } = t, a = {
      isRender: i,
      dts: s,
      duration: n,
      isKeyframe: !1
    };
    this.audioDecodeStart(a), this.worker ? this.worker && this.worker.postMessage({ cmd: "decode", data: t }) : (o = this.decoder) == null || o.decode(t);
  }
  destroy() {
    var t;
    super.destroy(), this.worker ? (this.worker.destroy(), this.worker = void 0) : ((t = this.decoder) == null || t.destroy(), this.decoder = void 0);
  }
}
y(Mg, "CLASSNAME", Mt.AACDecoder);
const f4 = [
  -5504,
  -5248,
  -6016,
  -5760,
  -4480,
  -4224,
  -4992,
  -4736,
  -7552,
  -7296,
  -8064,
  -7808,
  -6528,
  -6272,
  -7040,
  -6784,
  -2752,
  -2624,
  -3008,
  -2880,
  -2240,
  -2112,
  -2496,
  -2368,
  -3776,
  -3648,
  -4032,
  -3904,
  -3264,
  -3136,
  -3520,
  -3392,
  -22016,
  -20992,
  -24064,
  -23040,
  -17920,
  -16896,
  -19968,
  -18944,
  -30208,
  -29184,
  -32256,
  -31232,
  -26112,
  -25088,
  -28160,
  -27136,
  -11008,
  -10496,
  -12032,
  -11520,
  -8960,
  -8448,
  -9984,
  -9472,
  -15104,
  -14592,
  -16128,
  -15616,
  -13056,
  -12544,
  -14080,
  -13568,
  -344,
  -328,
  -376,
  -360,
  -280,
  -264,
  -312,
  -296,
  -472,
  -456,
  -504,
  -488,
  -408,
  -392,
  -440,
  -424,
  -88,
  -72,
  -120,
  -104,
  -24,
  -8,
  -56,
  -40,
  -216,
  -200,
  -248,
  -232,
  -152,
  -136,
  -184,
  -168,
  -1376,
  -1312,
  -1504,
  -1440,
  -1120,
  -1056,
  -1248,
  -1184,
  -1888,
  -1824,
  -2016,
  -1952,
  -1632,
  -1568,
  -1760,
  -1696,
  -688,
  -656,
  -752,
  -720,
  -560,
  -528,
  -624,
  -592,
  -944,
  -912,
  -1008,
  -976,
  -816,
  -784,
  -880,
  -848,
  5504,
  5248,
  6016,
  5760,
  4480,
  4224,
  4992,
  4736,
  7552,
  7296,
  8064,
  7808,
  6528,
  6272,
  7040,
  6784,
  2752,
  2624,
  3008,
  2880,
  2240,
  2112,
  2496,
  2368,
  3776,
  3648,
  4032,
  3904,
  3264,
  3136,
  3520,
  3392,
  22016,
  20992,
  24064,
  23040,
  17920,
  16896,
  19968,
  18944,
  30208,
  29184,
  32256,
  31232,
  26112,
  25088,
  28160,
  27136,
  11008,
  10496,
  12032,
  11520,
  8960,
  8448,
  9984,
  9472,
  15104,
  14592,
  16128,
  15616,
  13056,
  12544,
  14080,
  13568,
  344,
  328,
  376,
  360,
  280,
  264,
  312,
  296,
  472,
  456,
  504,
  488,
  408,
  392,
  440,
  424,
  88,
  72,
  120,
  104,
  24,
  8,
  56,
  40,
  216,
  200,
  248,
  232,
  152,
  136,
  184,
  168,
  1376,
  1312,
  1504,
  1440,
  1120,
  1056,
  1248,
  1184,
  1888,
  1824,
  2016,
  1952,
  1632,
  1568,
  1760,
  1696,
  688,
  656,
  752,
  720,
  560,
  528,
  624,
  592,
  944,
  912,
  1008,
  976,
  816,
  784,
  880,
  848
], Hf = 32635, p4 = new Int8Array([
  1,
  1,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  5,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  6,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7,
  7
]);
function m4(r) {
  let e, t, i, s;
  return e = ~r >> 8 & 128, e != 128 && (r = -r), r > Hf && (r = Hf), r >= 256 ? (t = p4[r >> 8 & 127], i = r >> t + 3 & 15, s = t << 4 | i) : s = r >> 4, s ^= e ^ 85, s;
}
const Bg = {
  /**
   * PCM转G711
   *
   * @param srcBuf    编码前的数据 arraybuffer
   * @param offset 偏移量
   * @param len    长度
   * @param res    编码后存放的数据
   * @return 编码后res数组长度应为编码前src数组长度的一半
   */
  encode(r, e = 0) {
    const t = new Int8Array(r);
    let i = e, s = t.length / 2;
    const n = new Int8Array(s);
    let a = 0;
    for (let o = 0; o < s; o++)
      a = t[i++] & 255 | t[i++] << 8, n[o] = m4(a);
    return n.buffer;
  },
  /**
   * G711A转PCM
   *
   * @param src    解码前的数据 arraybuffer
   * @param offset 偏移量
   * @param len    长度
   * @return res    解码后存放的数据 解码后res数组长度应为解码前src数组长度的两倍
   *
   */
  decode(r, e = 0) {
    const t = new Int8Array(r), i = t.length, s = new Int8Array(2 * i);
    for (let n = 0, a = 0; n < i; n++) {
      let o = f4[t[n + e] & 255];
      s[a++] = o, s[a++] = o >> 8;
    }
    return s.buffer;
  }
};
class g4 extends ve {
  constructor() {
    super();
  }
  decode(e, t) {
    const { data: i } = e;
    try {
      const s = Bg.decode(i.buffer), n = new Int16Array(s);
      this.emit("data", [n, n.length, t]);
    } catch (s) {
      this.emit("error", s);
    }
  }
  destroy() {
    this.removeAllListeners();
  }
}
const Fg = " ", _4 = (r) => Uint8Array.from(atob(r), (e) => e.charCodeAt(0)), Zf = typeof self < "u" && self.Blob && new Blob([_4(Fg)], { type: "text/javascript;charset=utf-8" });
function y4(r) {
  let e;
  try {
    if (e = Zf && (self.URL || self.webkitURL).createObjectURL(Zf), !e) throw "";
    const t = new Worker(e, {
      name: r == null ? void 0 : r.name
    });
    return t.addEventListener("error", () => {
      (self.URL || self.webkitURL).revokeObjectURL(e);
    }), t;
  } catch {
    return new Worker(
      "data:text/javascript;base64," + Fg,
      {
        name: r == null ? void 0 : r.name
      }
    );
  } finally {
    e && (self.URL || self.webkitURL).revokeObjectURL(e);
  }
}
class Og extends Rd {
  constructor(t, i) {
    const { enableAudioWorker: s, manaulGCInterval: n, traceId: a } = i;
    super(Mt.G711Decoder, t.codecType, a);
    y(this, "worker");
    y(this, "decoder");
    y(this, "onWorkerMessage", (t) => {
      let i = t.data;
      const [s, n, a] = i.data;
      switch (i.msg) {
        case "data":
          this.audioDecodeEnd(s, n, a);
          break;
        case "error":
          this.decodeError(t);
          break;
      }
    });
    if (s && typeof Worker < "u")
      try {
        this.worker = new _s(new y4(), Us.DecodeG711Audio, a), this.worker.onWorkerMessage = this.onWorkerMessage, this.worker.init({ manaulGCInterval: n }, a);
      } catch (o) {
        S.e(this.TAG, "Error while initialize WCSAudioDecoder worker, fallback to inline WCSAudioDecoder", (o == null ? void 0 : o.message) || (o == null ? void 0 : o.stack) || (o == null ? void 0 : o.toString())), this.worker = void 0;
      }
    if (!this.worker) {
      const o = this.decoder = new g4();
      o.on("data", (c) => this.audioDecodeEnd(c)), o.on("error", this.decodeError);
    }
  }
  decode(t, i) {
    var o, c;
    const { dts: s, duration: n } = t, a = {
      isRender: i,
      dts: s,
      duration: n,
      isKeyframe: !1
    };
    this.audioDecodeStart(a), this.worker ? (o = this.worker) == null || o.postMessage({ cmd: "decode", data: t, isRender: i }) : (c = this.decoder) == null || c.decode(t, i);
  }
  destroy() {
    var t;
    super.destroy(), this.worker ? this.worker.destroy() : ((t = this.decoder) == null || t.destroy(), this.decoder = void 0);
  }
}
y(Og, "CLASSNAME", Mt.G711Decoder);
const x4 = je.getFeatureList();
class v4 extends ve {
  /**
   *
   * @param {*} metaData
   * @param {*} config
   */
  constructor(t, i) {
    super();
    y(this, "type", "CompatiblePlayer");
    y(this, "TAG");
    y(this, "config");
    y(this, "videoMeta");
    y(this, "audioMeta");
    y(this, "videoCacheBuffer", []);
    y(this, "audioCacheBuffer", []);
    y(this, "player");
    y(this, "audioVolume", 1);
    y(this, "audioMuted", !1);
    y(this, "lastCheckTime", 0);
    y(this, "initPlayerFlag", !1);
    y(this, "checkDurationTimer");
    y(this, "initPlayerDelayTimer");
    y(this, "alreadCanPlay", !1);
    y(this, "lastVideoReceivedTime", 0);
    y(this, "playFirstVideoFlag", !1);
    y(this, "currentTime", 0);
    y(this, "initPlayer", async () => {
      S.d(this.TAG, "start init compatible player");
      let t;
      if (this.videoMeta)
        try {
          t = await this.getVideoDecoder(this.videoMeta);
        } catch (a) {
          S.e(this.TAG, "get video decoder , error =", (a == null ? void 0 : a.message) || (a == null ? void 0 : a.stack) || (a == null ? void 0 : a.toString()));
        }
      let i;
      if (this.audioMeta)
        try {
          i = await this.getAudioDecoder(this.audioMeta);
        } catch (a) {
          S.e(this.TAG, "get audio decoder , error =", (a == null ? void 0 : a.message) || (a == null ? void 0 : a.stack) || (a == null ? void 0 : a.toString()));
        }
      S.i(this.TAG, `VideoDecoderClass=${t == null ? void 0 : t.CLASSNAME} , AudioDecoderClass = ${i == null ? void 0 : i.CLASSNAME}`);
      let s = this.player = new e3({
        videoDecoderConstructor: t,
        audioDecoderConstructor: i,
        config: this.config,
        videoMeta: this.videoMeta,
        audioMeta: this.audioMeta
      });
      s.setVolume(this.audioVolume), [z.PLAYER_PAUSE, z.ERROR, z.PLAYER_NEED_RESTART, z.WCS_STATISTICS_INFO].forEach((a) => {
        s.on(a, (...o) => this.emit(a, ...o));
      }), s.on(z.TIME_UPDATE, (a) => {
        this.playerCallback(a);
      }), this.config.muted && (this.volume = 0), this.onWorkerLoaded();
    });
    y(this, "onWorkerLoaded", () => {
      setTimeout(() => {
        this.initPlayerFlag = !0, this.remuxVideo(), this.remuxAudio();
      }, 0);
    });
    this.TAG = S.traceTag(this.type, i.traceId), this.config = i, this.videoMeta = t.video, this.audioMeta = t.audio, setTimeout(this.initPlayer, 0);
  }
  set playbackRate(t) {
    var i;
    this.initPlayerFlag && ((i = this.player) == null || i.setPlaybackRate(t));
  }
  static setLogger(t, i) {
    S.setLogger(t), We.applyConfig(i);
  }
  destroy() {
    var t;
    S.i(this.TAG, "destory compatible player"), clearTimeout(this.checkDurationTimer), clearTimeout(this.initPlayerDelayTimer), this.removeAllListeners(), this.initPlayerFlag && ((t = this.player) == null || t.destroy(), this.player = void 0), this.initPlayerFlag = !1;
  }
  get paused() {
    var t;
    return this.initPlayerFlag ? ((t = this.player) == null ? void 0 : t.paused) ?? !1 : !0;
  }
  get volume() {
    return this.audioVolume;
  }
  set volume(t) {
    var i;
    this.audioVolume = t, (i = this.player) == null || i.setVolume(t);
  }
  set muted(t) {
    var i;
    this.audioMuted = t, (i = this.player) == null || i.setVolume(t ? 0 : this.audioVolume);
  }
  get muted() {
    return this.audioMuted;
  }
  pause() {
    var t;
    this.initPlayerFlag && ((t = this.player) == null || t.pause());
  }
  resume() {
    var t;
    this.initPlayerFlag && ((t = this.player) == null || t.resume());
  }
  stop() {
    var t;
    this.initPlayerFlag && ((t = this.player) == null || t.stop());
  }
  get buffered() {
    var t;
    if (this.initPlayerFlag)
      return (t = this.player) == null ? void 0 : t.buffered;
  }
  get duration() {
    var t;
    return this.initPlayerFlag ? (((t = this.player) == null ? void 0 : t.duration) ?? 0) / Zt : 0;
  }
  getVideoRender() {
    var t;
    return (t = this.player) == null ? void 0 : t.getVideoRender();
  }
  getAudioRender() {
    var t;
    return (t = this.player) == null ? void 0 : t.getAudioRender();
  }
  async getAudioDecoder(t) {
    return t ? await qa.isSupport(t) ? qa : ae.AAC === t.codecType ? Mg : ae.PCMA === t.codecType ? Og : void 0 : void 0;
  }
  async getVideoDecoder(t) {
    if (!t) return;
    const { nativeMP4H265Playback: i, supportVideoDecoder: s } = x4;
    let n = s && (t.codecType === de.H264 || t.codecType === de.H265 && i);
    return n = n && await _n.isSupport(t), n ? _n : void 0;
  }
  /*
  @brief playerCallback 播放器回调
  @param code 状态码  0 正常播放，1 出错
  @param time 播放时间偏移量
  @param timestamp 时间戳
  @param isSync 视频关键帧
   */
  playerCallback(t) {
    const { code: i, dts: s, ipcamTime: n, isSync: a = !1 } = t;
    i <= 0 && (this.currentTime = s / Zt, (s < this.lastCheckTime || s - this.lastCheckTime > 50) && (this.lastCheckTime = s, this.emit(z.TIME_UPDATE, null, { dts: s, ipcamTime: n, isSync: a })));
  }
  remuxAudio(t) {
    var s;
    const i = (s = this.audioMeta) == null ? void 0 : s.codecType;
    if (!(!i || i === ae.NONE)) {
      if (!this.initPlayerFlag) {
        t && this.audioCacheBuffer.push(t);
        return;
      }
      for (; this.audioCacheBuffer.length; ) {
        let n = this.audioCacheBuffer.shift();
        this.doRemuxAudio(n);
      }
      this.doRemuxAudio(t);
    }
  }
  doRemuxAudio(t) {
    if (!t) return;
    let { unit: i, dts: s } = t;
    this.playMedia(Rg, !1, i, s, !1);
  }
  remuxVideo(t) {
    var s;
    const i = (s = this.videoMeta) == null ? void 0 : s.codecType;
    if (!(!i || i === de.NONE)) {
      if (!this.initPlayerFlag) {
        t && this.videoCacheBuffer.push(t);
        return;
      }
      for (; this.videoCacheBuffer.length; ) {
        let n = this.videoCacheBuffer.shift();
        this.doRemuxVideo(n);
      }
      this.doRemuxVideo(t);
    }
  }
  doRemuxVideo(t) {
    if (!t) return;
    let { isStaticFrame: i, unit: s, dts: n, isKeyframe: a, ipcamTime: o, videoMeta: c = this.videoMeta } = t;
    o = o ?? n;
    const l = { ipcamTime: o, videoMeta: c, isStaticFrame: i };
    a && (this.videoMeta = c), i ? this.playMedia(-1, a, void 0, n, !1, l) : this.playMedia(-1, a, s, n, !1, l), this.playFirstVideoFlag && setTimeout(() => {
      this.emit(z.DURATION_CHANGE), this.emit(z.WCS_BUFFER_UPDATE);
    }, 0), this.playFirstVideoFlag = !0;
    const d = this.config, { isLive: h, liveBufferMS: u = 500, liveBufferStepMS: f = 150, liveBufferMaxMS: p = 4e3 } = d;
    if (h) {
      const m = Date.now();
      if (this.lastVideoReceivedTime) {
        const g = m - this.lastVideoReceivedTime;
        g > f * 2 && S.w(this.TAG, `receive video data, gap = ${g}.  buffer time =${u} step=${f}`), g > u + f && (d.liveBufferMS = Math.min(p, u + f), this.emit(z.WCS_LOADING));
      }
      this.lastVideoReceivedTime = m;
    }
  }
  playMedia(t, i, s, n, a, o) {
    var c;
    this.alreadCanPlay || (this.alreadCanPlay = !0, this.emit(z.CAN_PLAY)), (c = this.player) == null || c.play(t, i, s, n, a, o);
  }
}
class E4 {
  constructor(e, t) {
    y(this, "TAG", "PlayerEngineMainThread");
    y(this, "_emitter", new ve());
    y(this, "_media_data_source");
    y(this, "_config");
    y(this, "_media_element", null);
    y(this, "_mse_controller", null);
    y(this, "_transmuxer", null);
    y(this, "_pending_seek_time", null);
    y(this, "_seeking_handler", null);
    y(this, "_loading_controller", null);
    y(this, "_startup_stall_jumper", null);
    y(this, "_live_latency_chaser", null);
    y(this, "_live_latency_synchronizer", null);
    y(this, "_mse_source_opened", !1);
    y(this, "_has_pending_load", !1);
    y(this, "_loaded_metadata_received", !1);
    y(this, "_media_info", null);
    y(this, "_statistics_info", null);
    y(this, "e", null);
    y(this, "_compatiblePlayer", null);
    y(this, "onVideoResolutionChange", (e) => {
    });
    y(this, "_onvCanPlay", () => {
      this._receivedCanPlay = !0;
      const e = this._media_element;
      if (e.removeEventListener("canplay", this._onvCanPlay), e.autoplay) {
        let t = e.play();
        t !== void 0 && t.then(() => {
        }).catch((i) => {
          S.e(this.TAG, "Events.CAN_PLAY canot autoplay！", (i == null ? void 0 : i.message) || (i == null ? void 0 : i.stack) || (i == null ? void 0 : i.toString())), this.pause();
        });
      }
      this._emitter.emit(z.CAN_PLAY);
    });
    y(this, "_onvStalled", (e) => {
      S.w(this.TAG, "video play stalled!");
    });
    y(this, "_onvProgress", (e) => {
      S.w(this.TAG, "video play progress!");
    });
    y(this, "_onvEnd", (e) => {
      e && S.e(this.TAG, "_onvEnd", (e == null ? void 0 : e.message) || (e == null ? void 0 : e.stack) || (e == null ? void 0 : e.toString())), S.w(this.TAG, "media ended!"), this._emitter.emit(z.PLAY_ENDED, Ai.OTHER_ERROR, xa.MEDIA_MSE_ERROR, {
        timestamp: this.currentTime,
        isLive: this._config.isLive
      });
    });
    y(this, "_onvError", (e) => {
      var i;
      let t = ((i = this._media_element) == null ? void 0 : i.error) || {};
      S.w(this.TAG, `media error! code: ${t.code} msg:${t.message}`), this._emitter.emit(z.ERROR, Ai.MEDIA_ERROR, xa.MEDIA_MSE_ERROR, {
        timestamp: this.currentTime,
        isLive: this._config.isLive
      });
    });
    y(this, "_onvTimeUpdate", (e) => {
      const t = Math.round(this.currentTime * 1e3);
      this._emitter.emit(z.TIME_UPDATE, t);
    });
    this._media_data_source = e, this._config = Pr(), typeof t == "object" && Object.assign(this._config, t), e.isLive === !0 && (this._config.isLive = !0), this.e = {
      onMediaLoadedMetadata: this._onMediaLoadedMetadata.bind(this)
    };
  }
  destroy() {
    this._emitter.emit(z.DESTROYING), this._transmuxer && this.unload(), this._media_element && this.detachMediaElement(), this.e = null, this._media_data_source = null, this._emitter.removeAllListeners(), this._emitter = null;
  }
  on(e, t) {
    this._emitter.addListener(e, t), e === z.MEDIA_INFO && this._media_info ? Promise.resolve().then(() => this._emitter.emit(z.MEDIA_INFO, this.mediaInfo)) : e == z.STATISTICS_INFO && this._statistics_info && Promise.resolve().then(() => this._emitter.emit(z.STATISTICS_INFO, this.statisticsInfo));
  }
  off(e, t) {
    this._emitter.removeListener(e, t);
  }
  attachMediaElement(e) {
    this._media_element = e, e.src = "", e.removeAttribute("src"), e.srcObject = null, e.load(), e.addEventListener("loadedmetadata", this.e.onMediaLoadedMetadata);
  }
  initMSEController() {
    const e = this._media_element;
    e.addEventListener("canplay", this._onvCanPlay), e.addEventListener("stalled", this._onvStalled), e.addEventListener("progress", this._onvProgress), e.addEventListener("error", this._onvError), e.addEventListener("ended", this._onvEnd), e.addEventListener("timeupdate", this._onvTimeUpdate), this._mse_controller = new Sb(this._config), this._mse_controller.on(Dt.UPDATE_END, this._onMSEUpdateEnd.bind(this)), this._mse_controller.on(Dt.BUFFER_FULL, this._onMSEBufferFull.bind(this)), this._mse_controller.on(Dt.SOURCE_OPEN, this._onMSESourceOpen.bind(this)), this._mse_controller.on(Dt.ERROR, this._onMSEError.bind(this)), this._mse_controller.on(Dt.START_STREAMING, this._onMSEStartStreaming.bind(this)), this._mse_controller.on(Dt.END_STREAMING, this._onMSEEndStreaming.bind(this)), this._mse_controller.initialize({
      getCurrentTime: () => this._media_element.currentTime,
      getReadyState: () => this._media_element.readyState
    }), this._mse_controller.isManagedMediaSource() ? (e.disableRemotePlayback = !0, e.srcObject = this._mse_controller.getObject()) : e.src = this._mse_controller.getObjectURL();
  }
  detachMediaElement() {
    var e, t;
    this._media_element && ((e = this._mse_controller) == null || e.shutdown(), this._media_element.removeEventListener("loadedmetadata", this.e.onMediaLoadedMetadata), this._media_element.removeEventListener("canplay", this._onvCanPlay), this._media_element.removeEventListener("stalled", this._onvStalled), this._media_element.removeEventListener("progress", this._onvProgress), this._media_element.removeEventListener("error", this._onvError), this._media_element.removeEventListener("ended", this._onvEnd), this._media_element.removeEventListener("timeupdate", this._onvTimeUpdate), this._media_element.src = "", this._media_element.removeAttribute("src"), this._media_element.srcObject = null, this._media_element.load(), this._media_element = null, (t = this._mse_controller) == null || t.revokeObjectURL()), this._mse_controller && (this._mse_controller.destroy(), this._mse_controller = null), this._compatiblePlayer && (this._compatiblePlayer.destroy(), this._compatiblePlayer = null);
  }
  load() {
    if (!this._media_element)
      throw new qe("HTMLMediaElement must be attached before load()!");
    if (this._transmuxer)
      throw new qe("load() has been called, please call unload() first!");
    if (!this._has_pending_load) {
      if (this._config.deferLoadAfterSourceOpen && !this._mse_source_opened) {
        this._has_pending_load = !0;
        return;
      }
      this._transmuxer = new PA(this._media_data_source, this._config), this._transmuxer.on(X.INIT_SEGMENT, (e, t) => {
        var i;
        (i = this._mse_controller) == null || i.appendInitSegment(t);
      }), this._transmuxer.on(X.MEDIA_SEGMENT, (e, t) => {
        var i;
        (i = this._mse_controller) == null || i.appendMediaSegment(t), !this._config.isLive && e === "video" && t.data && t.data.byteLength > 0 && "info" in t && this._seeking_handler.appendSyncPoints(t.info.syncPoints), this._loading_controller.notifyBufferedPositionChanged(t.info.endDts / 1e3);
      }), this._transmuxer.on(X.LOADING_COMPLETE, () => {
        var e;
        (e = this._mse_controller) == null || e.endOfStream(), this._emitter.emit(z.LOADING_COMPLETE);
      }), this._transmuxer.on(X.RECOVERED_EARLY_EOF, () => {
        this._emitter.emit(z.RECOVERED_EARLY_EOF);
      }), this._transmuxer.on(X.IO_ERROR, (e, t) => {
        this._emitter.emit(z.ERROR, Ai.NETWORK_ERROR, e, t);
      }), this._transmuxer.on(X.DEMUX_ERROR, (e, t) => {
        this._emitter.emit(z.ERROR, Ai.MEDIA_ERROR, e, t);
      }), this._transmuxer.on(X.MEDIA_INFO, (e) => {
        this._media_info = e, this._emitter.emit(z.MEDIA_INFO, Object.assign({}, e));
      }), this._transmuxer.on(X.STATISTICS_INFO, (e) => {
        this._statistics_info = this._fillStatisticsInfo(e), this._emitter.emit(z.STATISTICS_INFO, Object.assign({}, e));
      }), this._transmuxer.on(X.RECOMMEND_SEEKPOINT, (e) => {
        this._media_element && !this._config.accurateSeek && this._seeking_handler.directSeek(e / 1e3);
      }), this._transmuxer.on(X.METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.SCRIPTDATA_ARRIVED, (e) => {
        this._emitter.emit(z.SCRIPTDATA_ARRIVED, e);
      }), this._transmuxer.on(X.TIMED_ID3_METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.TIMED_ID3_METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.PGS_SUBTITLE_ARRIVED, (e) => {
        this._emitter.emit(z.PGS_SUBTITLE_ARRIVED, e);
      }), this._transmuxer.on(X.SYNCHRONOUS_KLV_METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.SYNCHRONOUS_KLV_METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.ASYNCHRONOUS_KLV_METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.ASYNCHRONOUS_KLV_METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.SMPTE2038_METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.SMPTE2038_METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.SCTE35_METADATA_ARRIVED, (e) => {
        this._emitter.emit(z.SCTE35_METADATA_ARRIVED, e);
      }), this._transmuxer.on(X.PES_PRIVATE_DATA_DESCRIPTOR, (e) => {
        this._emitter.emit(z.PES_PRIVATE_DATA_DESCRIPTOR, e);
      }), this._transmuxer.on(X.PES_PRIVATE_DATA_ARRIVED, (e) => {
        this._emitter.emit(z.PES_PRIVATE_DATA_ARRIVED, e);
      }), this._transmuxer.on(X.CUSTOM_TRANSLATE_MESSAGE, (e) => {
        const { type: t, data: i } = e;
        S.d(this.TAG, "CUSTOM_TRANSLATE_MESSAGE", e), t === "mediaMeta" && this.onReceivedMediaInfo(i);
      }), this._transmuxer.on(X.LOADED_COMPATIBLE_VIDEO, (e) => {
        var t;
        (t = this._compatiblePlayer) == null || t.remuxVideo(e);
      }), this._transmuxer.on(X.LOADED_COMPATIBLE_AUDIO, (e) => {
        var t;
        (t = this._compatiblePlayer) == null || t.remuxAudio(e);
      }), this._transmuxer.on(X.NO_DATA_RECEIVED, () => {
        var e;
        this._isLoading = !1, (e = this._emitter) == null || e.emit(z.ERROR, Ai.NETWORK_ERROR, { code: -1, msg: "Long time no data received, timeout" }, null);
      }), this._seeking_handler = new Ja(this._config, this._media_element, this._onRequiredUnbufferedSeek.bind(this)), this._loading_controller = new kA(this._config, this._media_element, this._onRequestPauseTransmuxer.bind(this), this._onRequestResumeTransmuxer.bind(this)), this._startup_stall_jumper = new wA(this._media_element, this._onRequestDirectSeek.bind(this)), this._config.isLive && this._config.liveBufferLatencyChasing && (this._live_latency_chaser = new MA(this._config, this._media_element, this._onRequestDirectSeek.bind(this))), this._config.isLive && this._config.liveSync && (this._live_latency_synchronizer = new BA(this._config, this._media_element)), this._media_element.readyState > 0 && this._seeking_handler.directSeek(0), S.d(this.TAG, "transmuxer open"), this._transmuxer.open();
    }
  }
  /**
   *
   * @param {*} data
   * @returns true 停止
   */
  onReceivedMediaInfo(e) {
    var l, d;
    this._media_data_source;
    const t = this._metaData, { video: i = {}, audio: s = {} } = e, { codecWidth: n, codecHeight: a, codec: o } = i, { codec: c } = s;
    if (t) {
      const { codecWidth: h, codecHeight: u, codec: f } = t.video || {}, { codec: p } = t.audio || {};
      if (this._config.realtimeStream) {
        const m = f !== o, g = c !== p;
        if (m && S.w(this.TAG, `video codec changed,${f}->${o}`), g && S.w(this.TAG, `audio codec changed,${p}->${c}`), m || g)
          return (l = this._emitter) == null || l.emit(z.PLAYER_NEED_RESTART), !0;
      }
      h !== n && (S.w(this.TAG, `video resolution changed,${h}x${u}->${n}x${a}`), this.onVideoResolutionChange(i));
    }
    this._metaData = e, (d = this._emitter) == null || d.emit(z.META_UPDATE, e), this.createPlayer(e);
  }
  createPlayer(e) {
    const { video: t, audio: i } = e;
    let s = this._playTactics;
    const { hasVideo: n, hasAudio: a } = this._config;
    s || (s = this._playTactics = Gb(xc(t == null ? void 0 : t.codec), za(i == null ? void 0 : i.codec)));
    let { videoTactic: o, audioTactic: c } = s;
    n || (o = li.NONE), a || (c = li.NONE), this._transmuxer.setPlayTactics(s), !(this._compatiblePlayer || this._mse_controller) && (o === li.MSE && this.initMSEController(), (o === li.Compatible || c === li.Compatible) && this.createCompatiblePlayer(e, s));
  }
  get muted() {
    return this._mse_controller && this._media_element ? this._media_element.muted : this._compatiblePlayer ? this._compatiblePlayer.muted : !1;
  }
  set muted(e) {
    this._mse_controller && this._media_element ? this._media_element.muted = e : this._compatiblePlayer && (this._compatiblePlayer.muted = 0);
  }
  get volume() {
    return this._compatiblePlayer ? this._compatiblePlayer.volume : this._mse_controller ? this._media_element.volume : 0;
  }
  set volume(e) {
    this._compatiblePlayer ? this._compatiblePlayer.volume = e : this._mse_controller && (this._media_element.volume = e);
  }
  get currentTime() {
    return this._mse_controller && this._media_element ? this._media_element.currentTime : (this._compatiblePlayer && this._compatiblePlayer.currentTime, 0);
  }
  createCompatiblePlayer(e, t) {
    if (this._compatiblePlayer) return;
    let { videoTactic: i, audioTactic: s } = t;
    const { video: n, audio: a } = e, o = {};
    i === li.Compatible && (o.video = {
      codec: n.codec,
      codecType: xc(n.codec),
      codecWidth: n.codecWidth,
      codecHeight: n.codecHeight
    }), s === li.Compatible && (o.audio = {
      codec: a.codec,
      codecType: za(a.codec),
      audioSampleRate: a.audioSampleRate,
      channelCount: a.channelCount
    });
    let c = this._compatiblePlayer = new v4(o, this._config);
    (this._config.muted || !this._config.hasAudio) && (c.muted = !0);
    const { WCS_BUFFER_UPDATE: l, DURATION_CHANGE: d, ERROR: h, PLAYER_NEED_RESTART: u } = z;
    [h, u].forEach((p) => c.on(p, (...m) => {
      var g;
      return (g = this._emitter) == null ? void 0 : g.emit(p, ...m);
    })), this._mse_controller || (c.on(l, () => {
      var p;
      (p = this._emitter) == null || p.emit(l);
    }), c.on(d, () => {
      this._config.realtimeStream;
    }), this.onCompatiblePlayerEvent(c));
  }
  onCompatiblePlayerEvent(e) {
    [z.WCS_LOADING, z.TIME_UPDATE, z.ERROR, z.CAN_PLAY, z.PLAYER_PAUSE, z.PLAY_ENDED].forEach((i) => {
      e.on(i, (...s) => {
        var n;
        switch (i) {
          case z.CAN_PLAY:
            e.volume = this._volume ?? 1;
          default:
            (n = this._emitter) == null || n.emit(i, ...s);
            break;
        }
      });
    });
  }
  unload() {
    var e, t, i, s, n, a, o, c, l;
    (e = this._media_element) == null || e.pause(), (t = this._live_latency_synchronizer) == null || t.destroy(), this._live_latency_synchronizer = null, (i = this._live_latency_chaser) == null || i.destroy(), this._live_latency_chaser = null, (s = this._startup_stall_jumper) == null || s.destroy(), this._startup_stall_jumper = null, (n = this._loading_controller) == null || n.destroy(), this._loading_controller = null, (a = this._seeking_handler) == null || a.destroy(), this._seeking_handler = null, (o = this._mse_controller) == null || o.flush(), (c = this._transmuxer) == null || c.close(), (l = this._transmuxer) == null || l.destroy(), this._transmuxer = null;
  }
  play() {
    var e;
    return (e = this._media_element) == null ? void 0 : e.play();
  }
  pause() {
    var e;
    (e = this._media_element) == null || e.pause();
  }
  seek(e) {
  }
  get mediaInfo() {
    return Object.assign({}, this._media_info);
  }
  get statisticsInfo() {
    return Object.assign({}, this._statistics_info);
  }
  _onMSESourceOpen() {
    this._mse_source_opened = !0, this._has_pending_load && (this._has_pending_load = !1, this.load());
  }
  _onMSEUpdateEnd() {
    this._config.isLive && this._config.liveBufferLatencyChasing && this._live_latency_chaser && this._live_latency_chaser.notifyBufferedRangeUpdate(), this._loading_controller.notifyBufferedPositionChanged();
  }
  _onMSEBufferFull() {
    S.v(this.TAG, "MSE SourceBuffer is full, suspend transmuxing task"), this._loading_controller.suspendTransmuxer();
  }
  _onMSEError(e) {
    this._emitter.emit(z.ERROR, Ai.MEDIA_ERROR, xa.MEDIA_MSE_ERROR, e);
  }
  _onMSEStartStreaming() {
    this._loaded_metadata_received && (this._config.isLive || (S.v(this.TAG, "Resume transmuxing task due to ManagedMediaSource onStartStreaming"), this._loading_controller.resumeTransmuxer()));
  }
  _onMSEEndStreaming() {
    this._config.isLive || (S.v(this.TAG, "Suspend transmuxing task due to ManagedMediaSource onEndStreaming"), this._loading_controller.suspendTransmuxer());
  }
  _onMediaLoadedMetadata(e) {
    this._loaded_metadata_received = !0, this._pending_seek_time != null && (this._seeking_handler.seek(this._pending_seek_time), this._pending_seek_time = null);
  }
  _onRequestDirectSeek(e) {
    this._seeking_handler.directSeek(e);
  }
  _onRequiredUnbufferedSeek(e) {
    var t;
    (t = this._mse_controller) == null || t.flush(), this._transmuxer.seek(e);
  }
  _onRequestPauseTransmuxer() {
    this._transmuxer.pause();
  }
  _onRequestResumeTransmuxer() {
    this._transmuxer.resume();
  }
  _fillStatisticsInfo(e) {
    if (e.playerType = "MSEPlayer", !(this._media_element instanceof HTMLVideoElement))
      return e;
    let t = !0, i = 0, s = 0;
    if (this._media_element.getVideoPlaybackQuality) {
      const n = this._media_element.getVideoPlaybackQuality();
      i = n.totalVideoFrames, s = n.droppedVideoFrames;
    } else this._media_element.webkitDecodedFrameCount != null ? (i = this._media_element.webkitDecodedFrameCount, s = this._media_element.webkitDroppedFrameCount) : t = !1;
    return t && (e.decodedFrames = i, e.droppedFrames = s), e;
  }
}
class Ng {
  constructor(e, t) {
    y(this, "TAG", "MSEPlayer");
    y(this, "_type", "MSEPlayer");
    y(this, "_media_element", null);
    y(this, "_player_engine", null);
    y(this, "fakePlaybackRate", 1);
    y(this, "_config");
    const i = e.type.toLowerCase();
    if (i !== "mse" && i !== "mpegts" && i !== "m2ts" && i !== "flv")
      throw new Yi("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");
    this._config = t, this.initMediaElement(t);
    const s = { ...t, videoWrapper: void 0 };
    this._player_engine = new E4(e, s), this.attachMediaElement(this._media_element);
  }
  initMediaElement(e) {
    S.i(this.TAG, "initMediaElement");
    const { videoWrapper: t, muted: i, hasAudio: s } = e, n = i || !s ? "muted" : "", a = "player-type";
    let o = this._media_element = t.querySelector("video");
    o || (t.innerHTML = `<video autoplay webkit-playsinline="true" x-webkit-airplay="true" x5-playsinline="true" playsInline ${n} class="${Xs}-player-video-element">Your browser doesn't support HTML5 video.</video>`, o = this._media_element = t.querySelector("video")), o && (o.setAttribute(a, this.type), o.style.display = "block");
  }
  seekTo(e) {
    var i;
    const t = (i = this._config.extraOptions) == null ? void 0 : i.signalingProxy;
    t && (t.isSdCardReuse = !0, t == null || t.seekSdCard(e, yt.CMS));
  }
  set playbackRate(e) {
    this.fakePlaybackRate = e;
  }
  get playbackRate() {
    return this.fakePlaybackRate;
  }
  get videoRender() {
    return this._media_element;
  }
  get audioRender() {
    return this._media_element;
  }
  get metaData() {
    return {};
  }
  seek(e) {
    throw new Error("Method not implemented.");
  }
  destroy() {
    var t, i, s;
    const e = (t = this._config.extraOptions) == null ? void 0 : t.signalingProxy;
    e && ((i = e.playerDeviceInfo.seekParam) != null && i.isSDCard ? e == null || e.stopVod() : e == null || e.stopCmsLivePreview()), (s = this._player_engine) == null || s.destroy(), this._player_engine = null;
  }
  on(e, t) {
    this._player_engine.on(e, t);
  }
  off(e, t) {
    this._player_engine.off(e, t);
  }
  attachMediaElement(e) {
    this._media_element = e, this._player_engine.attachMediaElement(e);
  }
  detachMediaElement() {
    this._media_element = null, this._player_engine.detachMediaElement();
  }
  load() {
    this._player_engine.load();
  }
  unload() {
    this._player_engine.unload();
  }
  play() {
    return this._player_engine.play();
  }
  pause() {
    this.destroy();
  }
  get type() {
    return this._type;
  }
  get buffered() {
    return this._media_element.buffered;
  }
  get duration() {
    return this._media_element.duration;
  }
  get volume() {
    return this._player_engine.volume;
  }
  set volume(e) {
    this._player_engine.volume = e;
  }
  get muted() {
    return this._player_engine.muted;
  }
  set muted(e) {
    this._player_engine.muted = e;
  }
  get currentTime() {
    return this._player_engine ? this._player_engine.currentTime : 0;
  }
  set currentTime(e) {
    this._player_engine.seek(e);
  }
  get mediaInfo() {
    return this._player_engine.mediaInfo;
  }
  get statisticsInfo() {
    return this._player_engine.statisticsInfo;
  }
}
class Gg {
  constructor(e, t) {
    this.TAG = "NativePlayer", this._type = "NativePlayer", this._emitter = new ve(), this._config = Pr(), typeof t == "object" && Object.assign(this._config, t);
    let i = e.type.toLowerCase();
    if (i === "mse" || i === "mpegts" || i === "m2ts" || i === "flv")
      throw new Yi("NativePlayer does't support mse/mpegts/m2ts/flv MediaDataSource input!");
    if (e.hasOwnProperty("segments"))
      throw new Yi(`NativePlayer(${e.type}) doesn't support multipart playback!`);
    this.e = {
      onvLoadedMetadata: this._onvLoadedMetadata.bind(this)
    }, this._pendingSeekTime = null, this._statisticsReporter = null, this._mediaDataSource = e, this._mediaElement = null;
  }
  destroy() {
    this._emitter.emit(z.DESTROYING), this._mediaElement && (this.unload(), this.detachMediaElement()), this.e = null, this._mediaDataSource = null, this._emitter.removeAllListeners(), this._emitter = null;
  }
  on(e, t) {
    e === z.MEDIA_INFO ? this._mediaElement != null && this._mediaElement.readyState !== 0 && Promise.resolve().then(() => {
      this._emitter.emit(z.MEDIA_INFO, this.mediaInfo);
    }) : e === z.STATISTICS_INFO && this._mediaElement != null && this._mediaElement.readyState !== 0 && Promise.resolve().then(() => {
      this._emitter.emit(z.STATISTICS_INFO, this.statisticsInfo);
    }), this._emitter.addListener(e, t);
  }
  off(e, t) {
    this._emitter.removeListener(e, t);
  }
  attachMediaElement(e) {
    if (this._mediaElement = e, e.addEventListener("loadedmetadata", this.e.onvLoadedMetadata), this._pendingSeekTime != null)
      try {
        e.currentTime = this._pendingSeekTime, this._pendingSeekTime = null;
      } catch {
      }
  }
  detachMediaElement() {
    this._mediaElement && (this._mediaElement.src = "", this._mediaElement.removeAttribute("src"), this._mediaElement.removeEventListener("loadedmetadata", this.e.onvLoadedMetadata), this._mediaElement = null), this._statisticsReporter != null && (window.clearInterval(this._statisticsReporter), this._statisticsReporter = null);
  }
  load() {
    if (!this._mediaElement)
      throw new qe("HTMLMediaElement must be attached before load()!");
    this._mediaElement.src = this._mediaDataSource.url, this._mediaElement.readyState > 0 && (this._mediaElement.currentTime = 0), this._mediaElement.preload = "auto", this._mediaElement.load(), this._statisticsReporter = window.setInterval(
      this._reportStatisticsInfo.bind(this),
      this._config.statisticsInfoReportInterval
    );
  }
  unload() {
    this._mediaElement && (this._mediaElement.src = "", this._mediaElement.removeAttribute("src")), this._statisticsReporter != null && (window.clearInterval(this._statisticsReporter), this._statisticsReporter = null);
  }
  play() {
    return this._mediaElement.play();
  }
  pause() {
    this._mediaElement.pause();
  }
  get type() {
    return this._type;
  }
  get buffered() {
    return this._mediaElement.buffered;
  }
  get duration() {
    return this._mediaElement.duration;
  }
  get volume() {
    return this._mediaElement.volume;
  }
  set volume(e) {
    this._mediaElement.volume = e;
  }
  get muted() {
    return this._mediaElement.muted;
  }
  set muted(e) {
    this._mediaElement.muted = e;
  }
  get currentTime() {
    return this._mediaElement ? this._mediaElement.currentTime : 0;
  }
  set currentTime(e) {
    this._mediaElement ? this._mediaElement.currentTime = e : this._pendingSeekTime = e;
  }
  get mediaInfo() {
    let t = {
      mimeType: (this._mediaElement instanceof HTMLAudioElement ? "audio/" : "video/") + this._mediaDataSource.type
    };
    return this._mediaElement && (t.duration = Math.floor(this._mediaElement.duration * 1e3), this._mediaElement instanceof HTMLVideoElement && (t.width = this._mediaElement.videoWidth, t.height = this._mediaElement.videoHeight)), t;
  }
  get statisticsInfo() {
    let e = {
      playerType: this._type,
      url: this._mediaDataSource.url
    };
    if (!(this._mediaElement instanceof HTMLVideoElement))
      return e;
    let t = !0, i = 0, s = 0;
    if (this._mediaElement.getVideoPlaybackQuality) {
      let n = this._mediaElement.getVideoPlaybackQuality();
      i = n.totalVideoFrames, s = n.droppedVideoFrames;
    } else this._mediaElement.webkitDecodedFrameCount != null ? (i = this._mediaElement.webkitDecodedFrameCount, s = this._mediaElement.webkitDroppedFrameCount) : t = !1;
    return t && (e.decodedFrames = i, e.droppedFrames = s), e;
  }
  _onvLoadedMetadata(e) {
    this._pendingSeekTime != null && (this._mediaElement.currentTime = this._pendingSeekTime, this._pendingSeekTime = null), this._emitter.emit(z.MEDIA_INFO, this.mediaInfo);
  }
  _reportStatisticsInfo() {
    this._emitter.emit(z.STATISTICS_INFO, this.statisticsInfo);
  }
}
yg.install();
function S4(r, e) {
  let t = r;
  if (t == null || typeof t != "object")
    throw new Yi("MediaDataSource must be an javascript object!");
  if (!t.hasOwnProperty("type"))
    throw new Yi("MediaDataSource must has type field to indicate video file type!");
  switch (t.type) {
    case "mse":
    case "mpegts":
    case "m2ts":
    case "flv":
      return new Ng(t, e);
    default:
      return new Gg(t, e);
  }
}
function T4() {
  return je.supportMSEH264Playback();
}
function b4() {
  return je.getFeatureList();
}
let Ot = {};
Ot.createPlayer = S4;
Ot.isSupported = T4;
Ot.getFeatureList = b4;
Ot.BaseLoader = kn;
Ot.LoaderStatus = fe;
Ot.LoaderErrors = Ue;
Ot.Events = z;
Ot.ErrorTypes = Ai;
Ot.ErrorDetails = xa;
Ot.MSEPlayer = Ng;
Ot.NativePlayer = Gg;
Ot.LoggingControl = We;
Object.defineProperty(Ot, "version", {
  enumerable: !0,
  get: function() {
    return __VERSION__;
  }
});
const q = Number.isFinite || function(r) {
  return typeof r == "number" && isFinite(r);
}, A4 = Number.isSafeInteger || function(r) {
  return typeof r == "number" && Math.abs(r) <= C4;
}, C4 = Number.MAX_SAFE_INTEGER || 9007199254740991;
let ie = /* @__PURE__ */ function(r) {
  return r.NETWORK_ERROR = "networkError", r.MEDIA_ERROR = "mediaError", r.KEY_SYSTEM_ERROR = "keySystemError", r.MUX_ERROR = "muxError", r.OTHER_ERROR = "otherError", r;
}({}), V = /* @__PURE__ */ function(r) {
  return r.KEY_SYSTEM_NO_KEYS = "keySystemNoKeys", r.KEY_SYSTEM_NO_ACCESS = "keySystemNoAccess", r.KEY_SYSTEM_NO_SESSION = "keySystemNoSession", r.KEY_SYSTEM_NO_CONFIGURED_LICENSE = "keySystemNoConfiguredLicense", r.KEY_SYSTEM_LICENSE_REQUEST_FAILED = "keySystemLicenseRequestFailed", r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED = "keySystemServerCertificateRequestFailed", r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED = "keySystemServerCertificateUpdateFailed", r.KEY_SYSTEM_SESSION_UPDATE_FAILED = "keySystemSessionUpdateFailed", r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED = "keySystemStatusOutputRestricted", r.KEY_SYSTEM_STATUS_INTERNAL_ERROR = "keySystemStatusInternalError", r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR = "keySystemDestroyMediaKeysError", r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR = "keySystemDestroyCloseSessionError", r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR = "keySystemDestroyRemoveSessionError", r.MANIFEST_LOAD_ERROR = "manifestLoadError", r.MANIFEST_LOAD_TIMEOUT = "manifestLoadTimeOut", r.MANIFEST_PARSING_ERROR = "manifestParsingError", r.MANIFEST_INCOMPATIBLE_CODECS_ERROR = "manifestIncompatibleCodecsError", r.LEVEL_EMPTY_ERROR = "levelEmptyError", r.LEVEL_LOAD_ERROR = "levelLoadError", r.LEVEL_LOAD_TIMEOUT = "levelLoadTimeOut", r.LEVEL_PARSING_ERROR = "levelParsingError", r.LEVEL_SWITCH_ERROR = "levelSwitchError", r.AUDIO_TRACK_LOAD_ERROR = "audioTrackLoadError", r.AUDIO_TRACK_LOAD_TIMEOUT = "audioTrackLoadTimeOut", r.SUBTITLE_LOAD_ERROR = "subtitleTrackLoadError", r.SUBTITLE_TRACK_LOAD_TIMEOUT = "subtitleTrackLoadTimeOut", r.FRAG_LOAD_ERROR = "fragLoadError", r.FRAG_LOAD_TIMEOUT = "fragLoadTimeOut", r.FRAG_DECRYPT_ERROR = "fragDecryptError", r.FRAG_PARSING_ERROR = "fragParsingError", r.FRAG_GAP = "fragGap", r.REMUX_ALLOC_ERROR = "remuxAllocError", r.KEY_LOAD_ERROR = "keyLoadError", r.KEY_LOAD_TIMEOUT = "keyLoadTimeOut", r.BUFFER_ADD_CODEC_ERROR = "bufferAddCodecError", r.BUFFER_INCOMPATIBLE_CODECS_ERROR = "bufferIncompatibleCodecsError", r.BUFFER_APPEND_ERROR = "bufferAppendError", r.BUFFER_APPENDING_ERROR = "bufferAppendingError", r.BUFFER_STALLED_ERROR = "bufferStalledError", r.BUFFER_FULL_ERROR = "bufferFullError", r.BUFFER_SEEK_OVER_HOLE = "bufferSeekOverHole", r.BUFFER_NUDGE_ON_STALL = "bufferNudgeOnStall", r.ASSET_LIST_LOAD_ERROR = "assetListLoadError", r.ASSET_LIST_LOAD_TIMEOUT = "assetListLoadTimeout", r.ASSET_LIST_PARSING_ERROR = "assetListParsingError", r.INTERSTITIAL_ASSET_ITEM_ERROR = "interstitialAssetItemError", r.INTERNAL_EXCEPTION = "internalException", r.INTERNAL_ABORTED = "aborted", r.ATTACH_MEDIA_ERROR = "attachMediaError", r.UNKNOWN = "unknown", r;
}({}), T = /* @__PURE__ */ function(r) {
  return r.MEDIA_ATTACHING = "hlsMediaAttaching", r.MEDIA_ATTACHED = "hlsMediaAttached", r.MEDIA_DETACHING = "hlsMediaDetaching", r.MEDIA_DETACHED = "hlsMediaDetached", r.MEDIA_ENDED = "hlsMediaEnded", r.STALL_RESOLVED = "hlsStallResolved", r.BUFFER_RESET = "hlsBufferReset", r.BUFFER_CODECS = "hlsBufferCodecs", r.BUFFER_CREATED = "hlsBufferCreated", r.BUFFER_APPENDING = "hlsBufferAppending", r.BUFFER_APPENDED = "hlsBufferAppended", r.BUFFER_EOS = "hlsBufferEos", r.BUFFERED_TO_END = "hlsBufferedToEnd", r.BUFFER_FLUSHING = "hlsBufferFlushing", r.BUFFER_FLUSHED = "hlsBufferFlushed", r.MANIFEST_LOADING = "hlsManifestLoading", r.MANIFEST_LOADED = "hlsManifestLoaded", r.MANIFEST_PARSED = "hlsManifestParsed", r.LEVEL_SWITCHING = "hlsLevelSwitching", r.LEVEL_SWITCHED = "hlsLevelSwitched", r.LEVEL_LOADING = "hlsLevelLoading", r.LEVEL_LOADED = "hlsLevelLoaded", r.LEVEL_UPDATED = "hlsLevelUpdated", r.LEVEL_PTS_UPDATED = "hlsLevelPtsUpdated", r.LEVELS_UPDATED = "hlsLevelsUpdated", r.AUDIO_TRACKS_UPDATED = "hlsAudioTracksUpdated", r.AUDIO_TRACK_SWITCHING = "hlsAudioTrackSwitching", r.AUDIO_TRACK_SWITCHED = "hlsAudioTrackSwitched", r.AUDIO_TRACK_LOADING = "hlsAudioTrackLoading", r.AUDIO_TRACK_LOADED = "hlsAudioTrackLoaded", r.AUDIO_TRACK_UPDATED = "hlsAudioTrackUpdated", r.SUBTITLE_TRACKS_UPDATED = "hlsSubtitleTracksUpdated", r.SUBTITLE_TRACKS_CLEARED = "hlsSubtitleTracksCleared", r.SUBTITLE_TRACK_SWITCH = "hlsSubtitleTrackSwitch", r.SUBTITLE_TRACK_LOADING = "hlsSubtitleTrackLoading", r.SUBTITLE_TRACK_LOADED = "hlsSubtitleTrackLoaded", r.SUBTITLE_TRACK_UPDATED = "hlsSubtitleTrackUpdated", r.SUBTITLE_FRAG_PROCESSED = "hlsSubtitleFragProcessed", r.CUES_PARSED = "hlsCuesParsed", r.NON_NATIVE_TEXT_TRACKS_FOUND = "hlsNonNativeTextTracksFound", r.INIT_PTS_FOUND = "hlsInitPtsFound", r.FRAG_LOADING = "hlsFragLoading", r.FRAG_LOAD_EMERGENCY_ABORTED = "hlsFragLoadEmergencyAborted", r.FRAG_LOADED = "hlsFragLoaded", r.FRAG_DECRYPTED = "hlsFragDecrypted", r.FRAG_PARSING_INIT_SEGMENT = "hlsFragParsingInitSegment", r.FRAG_PARSING_USERDATA = "hlsFragParsingUserdata", r.FRAG_PARSING_METADATA = "hlsFragParsingMetadata", r.FRAG_PARSED = "hlsFragParsed", r.FRAG_BUFFERED = "hlsFragBuffered", r.FRAG_CHANGED = "hlsFragChanged", r.FPS_DROP = "hlsFpsDrop", r.FPS_DROP_LEVEL_CAPPING = "hlsFpsDropLevelCapping", r.MAX_AUTO_LEVEL_UPDATED = "hlsMaxAutoLevelUpdated", r.ERROR = "hlsError", r.DESTROYING = "hlsDestroying", r.KEY_LOADING = "hlsKeyLoading", r.KEY_LOADED = "hlsKeyLoaded", r.LIVE_BACK_BUFFER_REACHED = "hlsLiveBackBufferReached", r.BACK_BUFFER_REACHED = "hlsBackBufferReached", r.STEERING_MANIFEST_LOADED = "hlsSteeringManifestLoaded", r.ASSET_LIST_LOADING = "hlsAssetListLoading", r.ASSET_LIST_LOADED = "hlsAssetListLoaded", r.INTERSTITIALS_UPDATED = "hlsInterstitialsUpdated", r.INTERSTITIALS_BUFFERED_TO_BOUNDARY = "hlsInterstitialsBufferedToBoundary", r.INTERSTITIAL_ASSET_PLAYER_CREATED = "hlsInterstitialAssetPlayerCreated", r.INTERSTITIAL_STARTED = "hlsInterstitialStarted", r.INTERSTITIAL_ASSET_STARTED = "hlsInterstitialAssetStarted", r.INTERSTITIAL_ASSET_ENDED = "hlsInterstitialAssetEnded", r.INTERSTITIAL_ASSET_ERROR = "hlsInterstitialAssetError", r.INTERSTITIAL_ENDED = "hlsInterstitialEnded", r.INTERSTITIALS_PRIMARY_RESUMED = "hlsInterstitialsPrimaryResumed", r.PLAYOUT_LIMIT_REACHED = "hlsPlayoutLimitReached", r.EVENT_CUE_ENTER = "hlsEventCueEnter", r;
}({});
var me = {
  MANIFEST: "manifest",
  LEVEL: "level",
  AUDIO_TRACK: "audioTrack",
  SUBTITLE_TRACK: "subtitleTrack"
}, te = {
  MAIN: "main",
  AUDIO: "audio",
  SUBTITLE: "subtitle"
};
class tr {
  //  About half of the estimated value will be from the last |halfLife| samples by weight.
  constructor(e, t = 0, i = 0) {
    this.halfLife = void 0, this.alpha_ = void 0, this.estimate_ = void 0, this.totalWeight_ = void 0, this.halfLife = e, this.alpha_ = e ? Math.exp(Math.log(0.5) / e) : 0, this.estimate_ = t, this.totalWeight_ = i;
  }
  sample(e, t) {
    const i = Math.pow(this.alpha_, e);
    this.estimate_ = t * (1 - i) + i * this.estimate_, this.totalWeight_ += e;
  }
  getTotalWeight() {
    return this.totalWeight_;
  }
  getEstimate() {
    if (this.alpha_) {
      const e = 1 - Math.pow(this.alpha_, this.totalWeight_);
      if (e)
        return this.estimate_ / e;
    }
    return this.estimate_;
  }
}
class R4 {
  constructor(e, t, i, s = 100) {
    this.defaultEstimate_ = void 0, this.minWeight_ = void 0, this.minDelayMs_ = void 0, this.slow_ = void 0, this.fast_ = void 0, this.defaultTTFB_ = void 0, this.ttfb_ = void 0, this.defaultEstimate_ = i, this.minWeight_ = 1e-3, this.minDelayMs_ = 50, this.slow_ = new tr(e), this.fast_ = new tr(t), this.defaultTTFB_ = s, this.ttfb_ = new tr(e);
  }
  update(e, t) {
    const {
      slow_: i,
      fast_: s,
      ttfb_: n
    } = this;
    i.halfLife !== e && (this.slow_ = new tr(e, i.getEstimate(), i.getTotalWeight())), s.halfLife !== t && (this.fast_ = new tr(t, s.getEstimate(), s.getTotalWeight())), n.halfLife !== e && (this.ttfb_ = new tr(e, n.getEstimate(), n.getTotalWeight()));
  }
  sample(e, t) {
    e = Math.max(e, this.minDelayMs_);
    const i = 8 * t, s = e / 1e3, n = i / s;
    this.fast_.sample(s, n), this.slow_.sample(s, n);
  }
  sampleTTFB(e) {
    const t = e / 1e3, i = Math.sqrt(2) * Math.exp(-Math.pow(t, 2) / 2);
    this.ttfb_.sample(i, Math.max(e, 5));
  }
  canEstimate() {
    return this.fast_.getTotalWeight() >= this.minWeight_;
  }
  getEstimate() {
    return this.canEstimate() ? Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()) : this.defaultEstimate_;
  }
  getEstimateTTFB() {
    return this.ttfb_.getTotalWeight() >= this.minWeight_ ? this.ttfb_.getEstimate() : this.defaultTTFB_;
  }
  get defaultEstimate() {
    return this.defaultEstimate_;
  }
  destroy() {
  }
}
function I4(r, e, t) {
  return (e = D4(e)) in r ? Object.defineProperty(r, e, {
    value: t,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : r[e] = t, r;
}
function Me() {
  return Me = Object.assign ? Object.assign.bind() : function(r) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var i in t) ({}).hasOwnProperty.call(t, i) && (r[i] = t[i]);
    }
    return r;
  }, Me.apply(null, arguments);
}
function $f(r, e) {
  var t = Object.keys(r);
  if (Object.getOwnPropertySymbols) {
    var i = Object.getOwnPropertySymbols(r);
    e && (i = i.filter(function(s) {
      return Object.getOwnPropertyDescriptor(r, s).enumerable;
    })), t.push.apply(t, i);
  }
  return t;
}
function we(r) {
  for (var e = 1; e < arguments.length; e++) {
    var t = arguments[e] != null ? arguments[e] : {};
    e % 2 ? $f(Object(t), !0).forEach(function(i) {
      I4(r, i, t[i]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(r, Object.getOwnPropertyDescriptors(t)) : $f(Object(t)).forEach(function(i) {
      Object.defineProperty(r, i, Object.getOwnPropertyDescriptor(t, i));
    });
  }
  return r;
}
function L4(r, e) {
  if (typeof r != "object" || !r) return r;
  var t = r[Symbol.toPrimitive];
  if (t !== void 0) {
    var i = t.call(r, e);
    if (typeof i != "object") return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (e === "string" ? String : Number)(r);
}
function D4(r) {
  var e = L4(r, "string");
  return typeof e == "symbol" ? e : e + "";
}
class qt {
  constructor(e, t) {
    this.trace = void 0, this.debug = void 0, this.log = void 0, this.warn = void 0, this.info = void 0, this.error = void 0;
    const i = `[${e}]:`;
    this.trace = as, this.debug = t.debug.bind(null, i), this.log = t.log.bind(null, i), this.warn = t.warn.bind(null, i), this.info = t.info.bind(null, i), this.error = t.error.bind(null, i);
  }
}
const as = function() {
}, P4 = {
  trace: as,
  debug: as,
  log: as,
  warn: as,
  info: as,
  error: as
};
function Rc() {
  return Me({}, P4);
}
function k4(r, e) {
  const t = self.console[r];
  return t ? t.bind(self.console, `${e ? "[" + e + "] " : ""}[${r}] >`) : as;
}
function Kf(r, e, t) {
  return e[r] ? e[r].bind(e) : k4(r, t);
}
const Ic = Rc();
function w4(r, e, t) {
  const i = Rc();
  if (typeof console == "object" && r === !0 || typeof r == "object") {
    const s = [
      // Remove out from list here to hard-disable a log-level
      // 'trace',
      "debug",
      "log",
      "info",
      "warn",
      "error"
    ];
    s.forEach((n) => {
      i[n] = Kf(n, r, t);
    });
    try {
      i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.11`);
    } catch {
      return Rc();
    }
    s.forEach((n) => {
      Ic[n] = Kf(n, r);
    });
  } else
    Me(Ic, i);
  return i;
}
const Pe = Ic;
function ys(r = !0) {
  return typeof self > "u" ? void 0 : (r || !self.MediaSource) && self.ManagedMediaSource || self.MediaSource || self.WebKitMediaSource;
}
function M4(r) {
  return typeof self < "u" && r === self.ManagedMediaSource;
}
function Ug(r, e) {
  const t = Object.keys(r), i = Object.keys(e), s = t.length, n = i.length;
  return !s || !n || s === n && !t.some((a) => i.indexOf(a) === -1);
}
function $t(r, e = !1) {
  if (typeof TextDecoder < "u") {
    const l = new TextDecoder("utf-8").decode(r);
    if (e) {
      const d = l.indexOf("\0");
      return d !== -1 ? l.substring(0, d) : l;
    }
    return l.replace(/\0/g, "");
  }
  const t = r.length;
  let i, s, n, a = "", o = 0;
  for (; o < t; ) {
    if (i = r[o++], i === 0 && e)
      return a;
    if (i === 0 || i === 3)
      continue;
    switch (i >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        a += String.fromCharCode(i);
        break;
      case 12:
      case 13:
        s = r[o++], a += String.fromCharCode((i & 31) << 6 | s & 63);
        break;
      case 14:
        s = r[o++], n = r[o++], a += String.fromCharCode((i & 15) << 12 | (s & 63) << 6 | (n & 63) << 0);
        break;
    }
  }
  return a;
}
function Wt(r) {
  let e = "";
  for (let t = 0; t < r.length; t++) {
    let i = r[t].toString(16);
    i.length < 2 && (i = "0" + i), e += i;
  }
  return e;
}
function Vg(r) {
  return Uint8Array.from(r.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
}
function B4(r) {
  return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
}
var g0 = { exports: {} }, Xf;
function F4() {
  return Xf || (Xf = 1, function(r, e) {
    (function(t) {
      var i = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/, s = /^(?=([^\/?#]*))\1([^]*)$/, n = /(?:\/|^)\.(?=\/)/g, a = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g, o = {
        // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
        // E.g
        // With opts.alwaysNormalize = false (default, spec compliant)
        // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
        // With opts.alwaysNormalize = true (not spec compliant)
        // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
        buildAbsoluteURL: function(c, l, d) {
          if (d = d || {}, c = c.trim(), l = l.trim(), !l) {
            if (!d.alwaysNormalize)
              return c;
            var h = o.parseURL(c);
            if (!h)
              throw new Error("Error trying to parse base URL.");
            return h.path = o.normalizePath(
              h.path
            ), o.buildURLFromParts(h);
          }
          var u = o.parseURL(l);
          if (!u)
            throw new Error("Error trying to parse relative URL.");
          if (u.scheme)
            return d.alwaysNormalize ? (u.path = o.normalizePath(u.path), o.buildURLFromParts(u)) : l;
          var f = o.parseURL(c);
          if (!f)
            throw new Error("Error trying to parse base URL.");
          if (!f.netLoc && f.path && f.path[0] !== "/") {
            var p = s.exec(f.path);
            f.netLoc = p[1], f.path = p[2];
          }
          f.netLoc && !f.path && (f.path = "/");
          var m = {
            // 2c) Otherwise, the embedded URL inherits the scheme of
            // the base URL.
            scheme: f.scheme,
            netLoc: u.netLoc,
            path: null,
            params: u.params,
            query: u.query,
            fragment: u.fragment
          };
          if (!u.netLoc && (m.netLoc = f.netLoc, u.path[0] !== "/"))
            if (!u.path)
              m.path = f.path, u.params || (m.params = f.params, u.query || (m.query = f.query));
            else {
              var g = f.path, x = g.substring(0, g.lastIndexOf("/") + 1) + u.path;
              m.path = o.normalizePath(x);
            }
          return m.path === null && (m.path = d.alwaysNormalize ? o.normalizePath(u.path) : u.path), o.buildURLFromParts(m);
        },
        parseURL: function(c) {
          var l = i.exec(c);
          return l ? {
            scheme: l[1] || "",
            netLoc: l[2] || "",
            path: l[3] || "",
            params: l[4] || "",
            query: l[5] || "",
            fragment: l[6] || ""
          } : null;
        },
        normalizePath: function(c) {
          for (c = c.split("").reverse().join("").replace(n, ""); c.length !== (c = c.replace(a, "")).length; )
            ;
          return c.split("").reverse().join("");
        },
        buildURLFromParts: function(c) {
          return c.scheme + c.netLoc + c.path + c.params + c.query + c.fragment;
        }
      };
      r.exports = o;
    })();
  }(g0)), g0.exports;
}
var Nd = F4();
class Gd {
  constructor() {
    this.aborted = !1, this.loaded = 0, this.retry = 0, this.total = 0, this.chunkCount = 0, this.bwEstimate = 0, this.loading = {
      start: 0,
      first: 0,
      end: 0
    }, this.parsing = {
      start: 0,
      end: 0
    }, this.buffering = {
      start: 0,
      first: 0,
      end: 0
    };
  }
}
var Oe = {
  AUDIO: "audio",
  VIDEO: "video",
  AUDIOVIDEO: "audiovideo"
};
class Wg {
  constructor(e) {
    this._byteRange = null, this._url = null, this._stats = null, this._streams = null, this.base = void 0, this.relurl = void 0, typeof e == "string" && (e = {
      url: e
    }), this.base = e, N4(this, "stats");
  }
  // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  setByteRange(e, t) {
    const i = e.split("@", 2);
    let s;
    i.length === 1 ? s = (t == null ? void 0 : t.byteRangeEndOffset) || 0 : s = parseInt(i[1]), this._byteRange = [s, parseInt(i[0]) + s];
  }
  get baseurl() {
    return this.base.url;
  }
  get byteRange() {
    return this._byteRange === null ? [] : this._byteRange;
  }
  get byteRangeStartOffset() {
    return this.byteRange[0];
  }
  get byteRangeEndOffset() {
    return this.byteRange[1];
  }
  get elementaryStreams() {
    return this._streams === null && (this._streams = {
      [Oe.AUDIO]: null,
      [Oe.VIDEO]: null,
      [Oe.AUDIOVIDEO]: null
    }), this._streams;
  }
  set elementaryStreams(e) {
    this._streams = e;
  }
  get hasStats() {
    return this._stats !== null;
  }
  get hasStreams() {
    return this._streams !== null;
  }
  get stats() {
    return this._stats === null && (this._stats = new Gd()), this._stats;
  }
  set stats(e) {
    this._stats = e;
  }
  get url() {
    return !this._url && this.baseurl && this.relurl && (this._url = Nd.buildAbsoluteURL(this.baseurl, this.relurl, {
      alwaysNormalize: !0
    })), this._url || "";
  }
  set url(e) {
    this._url = e;
  }
  clearElementaryStreamInfo() {
    const {
      elementaryStreams: e
    } = this;
    e[Oe.AUDIO] = null, e[Oe.VIDEO] = null, e[Oe.AUDIOVIDEO] = null;
  }
}
function et(r) {
  return r.sn !== "initSegment";
}
class _0 extends Wg {
  constructor(e, t) {
    super(t), this._decryptdata = null, this._programDateTime = null, this._ref = null, this._bitrate = void 0, this.rawProgramDateTime = null, this.tagList = [], this.duration = 0, this.sn = 0, this.levelkeys = void 0, this.type = void 0, this.loader = null, this.keyLoader = null, this.level = -1, this.cc = 0, this.startPTS = void 0, this.endPTS = void 0, this.startDTS = void 0, this.endDTS = void 0, this.start = 0, this.playlistOffset = 0, this.deltaPTS = void 0, this.maxStartPTS = void 0, this.minEndPTS = void 0, this.data = void 0, this.bitrateTest = !1, this.title = null, this.initSegment = null, this.endList = void 0, this.gap = void 0, this.urlId = 0, this.type = e;
  }
  get byteLength() {
    if (this.hasStats) {
      const e = this.stats.total;
      if (e)
        return e;
    }
    if (this.byteRange.length) {
      const e = this.byteRange[0], t = this.byteRange[1];
      if (q(e) && q(t))
        return t - e;
    }
    return null;
  }
  get bitrate() {
    return this.byteLength ? this.byteLength * 8 / this.duration : this._bitrate ? this._bitrate : null;
  }
  set bitrate(e) {
    this._bitrate = e;
  }
  get decryptdata() {
    const {
      levelkeys: e
    } = this;
    if (!e && !this._decryptdata)
      return null;
    if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
      const t = this.levelkeys.identity;
      if (t)
        this._decryptdata = t.getDecryptData(this.sn);
      else {
        const i = Object.keys(this.levelkeys);
        if (i.length === 1) {
          const s = this._decryptdata = this.levelkeys[i[0]] || null;
          if (s)
            return s.getDecryptData(this.sn);
        }
      }
    }
    return this._decryptdata;
  }
  get end() {
    return this.start + this.duration;
  }
  get endProgramDateTime() {
    if (this.programDateTime === null)
      return null;
    const e = q(this.duration) ? this.duration : 0;
    return this.programDateTime + e * 1e3;
  }
  get encrypted() {
    var e;
    if ((e = this._decryptdata) != null && e.encrypted)
      return !0;
    if (this.levelkeys) {
      var t;
      const i = Object.keys(this.levelkeys), s = i.length;
      if (s > 1 || s === 1 && (t = this.levelkeys[i[0]]) != null && t.encrypted)
        return !0;
    }
    return !1;
  }
  get programDateTime() {
    return this._programDateTime === null && this.rawProgramDateTime && (this.programDateTime = Date.parse(this.rawProgramDateTime)), this._programDateTime;
  }
  set programDateTime(e) {
    if (!q(e)) {
      this._programDateTime = this.rawProgramDateTime = null;
      return;
    }
    this._programDateTime = e;
  }
  get ref() {
    return et(this) ? (this._ref || (this._ref = {
      base: this.base,
      start: this.start,
      duration: this.duration,
      sn: this.sn,
      programDateTime: this.programDateTime
    }), this._ref) : null;
  }
  addStart(e) {
    this.setStart(this.start + e);
  }
  setStart(e) {
    this.start = e, this._ref && (this._ref.start = e);
  }
  setDuration(e) {
    this.duration = e, this._ref && (this._ref.duration = e);
  }
  setKeyFormat(e) {
    if (this.levelkeys) {
      const t = this.levelkeys[e];
      t && !this._decryptdata && (this._decryptdata = t.getDecryptData(this.sn));
    }
  }
  abortRequests() {
    var e, t;
    (e = this.loader) == null || e.abort(), (t = this.keyLoader) == null || t.abort();
  }
  setElementaryStreamInfo(e, t, i, s, n, a = !1) {
    const {
      elementaryStreams: o
    } = this, c = o[e];
    if (!c) {
      o[e] = {
        startPTS: t,
        endPTS: i,
        startDTS: s,
        endDTS: n,
        partial: a
      };
      return;
    }
    c.startPTS = Math.min(c.startPTS, t), c.endPTS = Math.max(c.endPTS, i), c.startDTS = Math.min(c.startDTS, s), c.endDTS = Math.max(c.endDTS, n);
  }
}
class O4 extends Wg {
  constructor(e, t, i, s, n) {
    super(i), this.fragOffset = 0, this.duration = 0, this.gap = !1, this.independent = !1, this.relurl = void 0, this.fragment = void 0, this.index = void 0, this.duration = e.decimalFloatingPoint("DURATION"), this.gap = e.bool("GAP"), this.independent = e.bool("INDEPENDENT"), this.relurl = e.enumeratedString("URI"), this.fragment = t, this.index = s;
    const a = e.enumeratedString("BYTERANGE");
    a && this.setByteRange(a, n), n && (this.fragOffset = n.fragOffset + n.duration);
  }
  get start() {
    return this.fragment.start + this.fragOffset;
  }
  get end() {
    return this.start + this.duration;
  }
  get loaded() {
    const {
      elementaryStreams: e
    } = this;
    return !!(e.audio || e.video || e.audiovideo);
  }
}
function Hg(r, e) {
  const t = Object.getPrototypeOf(r);
  if (t) {
    const i = Object.getOwnPropertyDescriptor(t, e);
    return i || Hg(t, e);
  }
}
function N4(r, e) {
  const t = Hg(r, e);
  t && (t.enumerable = !0, Object.defineProperty(r, e, t));
}
const Yf = Math.pow(2, 32) - 1, G4 = [].push, Zg = {
  video: 1,
  audio: 2,
  id3: 3,
  text: 4
};
function st(r) {
  return String.fromCharCode.apply(null, r);
}
function $g(r, e) {
  const t = r[e] << 8 | r[e + 1];
  return t < 0 ? 65536 + t : t;
}
function oe(r, e) {
  const t = Kg(r, e);
  return t < 0 ? 4294967296 + t : t;
}
function zf(r, e) {
  let t = oe(r, e);
  return t *= Math.pow(2, 32), t += oe(r, e + 4), t;
}
function Kg(r, e) {
  return r[e] << 24 | r[e + 1] << 16 | r[e + 2] << 8 | r[e + 3];
}
function U4(r) {
  const e = r.byteLength;
  for (let t = 0; t < e; ) {
    const i = oe(r, t);
    if (i > 8 && r[t + 4] === 109 && r[t + 5] === 111 && r[t + 6] === 111 && r[t + 7] === 102)
      return !0;
    t = i > 1 ? t + i : e;
  }
  return !1;
}
function pe(r, e) {
  const t = [];
  if (!e.length)
    return t;
  const i = r.byteLength;
  for (let s = 0; s < i; ) {
    const n = oe(r, s), a = st(r.subarray(s + 4, s + 8)), o = n > 1 ? s + n : i;
    if (a === e[0])
      if (e.length === 1)
        t.push(r.subarray(s + 8, o));
      else {
        const c = pe(r.subarray(s + 8, o), e.slice(1));
        c.length && G4.apply(t, c);
      }
    s = o;
  }
  return t;
}
function V4(r) {
  const e = [], t = r[0];
  let i = 8;
  const s = oe(r, i);
  i += 4;
  let n = 0, a = 0;
  t === 0 ? (n = oe(r, i), a = oe(r, i + 4), i += 8) : (n = zf(r, i), a = zf(r, i + 8), i += 16), i += 2;
  let o = r.length + a;
  const c = $g(r, i);
  i += 2;
  for (let l = 0; l < c; l++) {
    let d = i;
    const h = oe(r, d);
    d += 4;
    const u = h & 2147483647;
    if ((h & 2147483648) >>> 31 === 1)
      return Pe.warn("SIDX has hierarchical references (not supported)"), null;
    const p = oe(r, d);
    d += 4, e.push({
      referenceSize: u,
      subsegmentDuration: p,
      // unscaled
      info: {
        duration: p / s,
        start: o,
        end: o + u - 1
      }
    }), o += u, d += 4, i = d;
  }
  return {
    earliestPresentationTime: n,
    timescale: s,
    version: t,
    referencesCount: c,
    references: e
  };
}
function Xg(r) {
  const e = [], t = pe(r, ["moov", "trak"]);
  for (let s = 0; s < t.length; s++) {
    const n = t[s], a = pe(n, ["tkhd"])[0];
    if (a) {
      let o = a[0];
      const c = oe(a, o === 0 ? 12 : 20), l = pe(n, ["mdia", "mdhd"])[0];
      if (l) {
        o = l[0];
        const d = oe(l, o === 0 ? 12 : 20), h = pe(n, ["mdia", "hdlr"])[0];
        if (h) {
          const u = st(h.subarray(8, 12)), f = {
            soun: Oe.AUDIO,
            vide: Oe.VIDEO
          }[u], p = pe(n, ["mdia", "minf", "stbl", "stsd"])[0], m = W4(p);
          f ? (e[c] = {
            timescale: d,
            type: f,
            stsd: m
          }, e[f] = we({
            timescale: d,
            id: c
          }, m)) : e[c] = {
            timescale: d,
            type: u,
            stsd: m
          };
        }
      }
    }
  }
  return pe(r, ["moov", "mvex", "trex"]).forEach((s) => {
    const n = oe(s, 4), a = e[n];
    a && (a.default = {
      duration: oe(s, 12),
      flags: oe(s, 20)
    });
  }), e;
}
function W4(r) {
  const e = r.subarray(8), t = e.subarray(86), i = st(e.subarray(4, 8));
  let s = i, n;
  const a = i === "enca" || i === "encv";
  if (a) {
    const l = pe(e, [i])[0].subarray(i === "enca" ? 28 : 78);
    pe(l, ["sinf"]).forEach((h) => {
      const u = pe(h, ["schm"])[0];
      if (u) {
        const f = st(u.subarray(4, 8));
        if (f === "cbcs" || f === "cenc") {
          const p = pe(h, ["frma"])[0];
          p && (s = st(p));
        }
      }
    });
  }
  const o = s;
  switch (s) {
    case "avc1":
    case "avc2":
    case "avc3":
    case "avc4": {
      const c = pe(t, ["avcC"])[0];
      c && c.length > 3 && (s += "." + jn(c[1]) + jn(c[2]) + jn(c[3]), n = zn(o === "avc1" ? "dva1" : "dvav", t));
      break;
    }
    case "mp4a": {
      const c = pe(e, [i])[0], l = pe(c.subarray(28), ["esds"])[0];
      if (l && l.length > 7) {
        let d = 4;
        if (l[d++] !== 3)
          break;
        d = y0(l, d), d += 2;
        const h = l[d++];
        if (h & 128 && (d += 2), h & 64 && (d += l[d++]), l[d++] !== 4)
          break;
        d = y0(l, d);
        const u = l[d++];
        if (u === 64)
          s += "." + jn(u);
        else
          break;
        if (d += 12, l[d++] !== 5)
          break;
        d = y0(l, d);
        const f = l[d++];
        let p = (f & 248) >> 3;
        p === 31 && (p += 1 + ((f & 7) << 3) + ((l[d] & 224) >> 5)), s += "." + p;
      }
      break;
    }
    case "hvc1":
    case "hev1": {
      const c = pe(t, ["hvcC"])[0];
      if (c && c.length > 12) {
        const l = c[1], d = ["", "A", "B", "C"][l >> 6], h = l & 31, u = oe(c, 2), f = (l & 32) >> 5 ? "H" : "L", p = c[12], m = c.subarray(6, 12);
        s += "." + d + h, s += "." + H4(u).toString(16).toUpperCase(), s += "." + f + p;
        let g = "";
        for (let x = m.length; x--; ) {
          const _ = m[x];
          (_ || g) && (g = "." + _.toString(16).toUpperCase() + g);
        }
        s += g;
      }
      n = zn(o == "hev1" ? "dvhe" : "dvh1", t);
      break;
    }
    case "dvh1":
    case "dvhe":
    case "dvav":
    case "dva1":
    case "dav1": {
      s = zn(s, t) || s;
      break;
    }
    case "vp09": {
      const c = pe(t, ["vpcC"])[0];
      if (c && c.length > 6) {
        const l = c[4], d = c[5], h = c[6] >> 4 & 15;
        s += "." + Si(l) + "." + Si(d) + "." + Si(h);
      }
      break;
    }
    case "av01": {
      const c = pe(t, ["av1C"])[0];
      if (c && c.length > 2) {
        const l = c[1] >>> 5, d = c[1] & 31, h = c[2] >>> 7 ? "H" : "M", u = (c[2] & 64) >> 6, f = (c[2] & 32) >> 5, p = l === 2 && u ? f ? 12 : 10 : u ? 10 : 8, m = (c[2] & 16) >> 4, g = (c[2] & 8) >> 3, x = (c[2] & 4) >> 2, _ = c[2] & 3;
        s += "." + l + "." + Si(d) + h + "." + Si(p) + "." + m + "." + g + x + _ + "." + Si(1) + "." + Si(1) + "." + Si(1) + "." + 0, n = zn("dav1", t);
      }
      break;
    }
  }
  return {
    codec: s,
    encrypted: a,
    supplemental: n
  };
}
function zn(r, e) {
  const t = pe(e, ["dvvC"]), i = t.length ? t[0] : pe(e, ["dvcC"])[0];
  if (i) {
    const s = i[2] >> 1 & 127, n = i[2] << 5 & 32 | i[3] >> 3 & 31;
    return r + "." + Si(s) + "." + Si(n);
  }
}
function H4(r) {
  let e = 0;
  for (let t = 0; t < 32; t++)
    e |= (r >> t & 1) << 31 - t;
  return e >>> 0;
}
function y0(r, e) {
  const t = e + 5;
  for (; r[e++] & 128 && e < t; )
    ;
  return e;
}
function jn(r) {
  return ("0" + r.toString(16).toUpperCase()).slice(-2);
}
function Si(r) {
  return (r < 10 ? "0" : "") + r;
}
function Z4(r, e) {
  if (!r || !e)
    return;
  const t = e.keyId;
  t && e.isCommonEncryption && pe(r, ["moov", "trak"]).forEach((s) => {
    const a = pe(s, ["mdia", "minf", "stbl", "stsd"])[0].subarray(8);
    let o = pe(a, ["enca"]);
    const c = o.length > 0;
    c || (o = pe(a, ["encv"])), o.forEach((l) => {
      const d = c ? l.subarray(28) : l.subarray(78);
      pe(d, ["sinf"]).forEach((u) => {
        const f = Yg(u);
        if (f) {
          const p = f.subarray(8, 24);
          p.some((m) => m !== 0) || (Pe.log(`[eme] Patching keyId in 'enc${c ? "a" : "v"}>sinf>>tenc' box: ${Wt(p)} -> ${Wt(t)}`), f.set(t, 8));
        }
      });
    });
  });
}
function Yg(r) {
  const e = pe(r, ["schm"])[0];
  if (e) {
    const t = st(e.subarray(4, 8));
    if (t === "cbcs" || t === "cenc")
      return pe(r, ["schi", "tenc"])[0];
  }
  return null;
}
function $4(r, e, t) {
  const i = {}, s = pe(r, ["moof", "traf"]);
  for (let n = 0; n < s.length; n++) {
    const a = s[n], o = pe(a, ["tfhd"])[0], c = oe(o, 4), l = e[c];
    if (!l)
      continue;
    i[c] || (i[c] = {
      start: NaN,
      duration: 0,
      sampleCount: 0,
      timescale: l.timescale,
      type: l.type
    });
    const d = i[c], h = pe(a, ["tfdt"])[0];
    if (h) {
      const v = h[0];
      let E = oe(h, 4);
      v === 1 && (E === Yf ? t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time") : (E *= Yf + 1, E += oe(h, 8))), q(E) && (!q(d.start) || E < d.start) && (d.start = E);
    }
    const u = l.default, f = oe(o, 0) | (u == null ? void 0 : u.flags);
    let p = (u == null ? void 0 : u.duration) || 0;
    f & 8 && (f & 2 ? p = oe(o, 12) : p = oe(o, 8));
    const m = pe(a, ["trun"]);
    let g = d.start || 0, x = 0, _ = p;
    for (let v = 0; v < m.length; v++) {
      const E = m[v], b = oe(E, 4), A = d.sampleCount;
      d.sampleCount += b;
      const C = E[3] & 1, I = E[3] & 4, L = E[2] & 1, R = E[2] & 2, D = E[2] & 4, M = E[2] & 8;
      let w = 8, N = b;
      for (C && (w += 4), I && b && (!(E[w + 1] & 1) && d.keyFrameIndex === void 0 && (d.keyFrameIndex = A), w += 4, L ? (_ = oe(E, w), w += 4) : _ = p, R && (w += 4), M && (w += 4), g += _, x += _, N--); N--; )
        L ? (_ = oe(E, w), w += 4) : _ = p, R && (w += 4), D && (E[w + 1] & 1 || d.keyFrameIndex === void 0 && (d.keyFrameIndex = d.sampleCount - (N + 1), d.keyFrameStart = g), w += 4), M && (w += 4), g += _, x += _;
      !x && p && (x += p * b);
    }
    d.duration += x;
  }
  if (!Object.keys(i).some((n) => i[n].duration)) {
    let n = 1 / 0, a = 0;
    const o = pe(r, ["sidx"]);
    for (let c = 0; c < o.length; c++) {
      const l = V4(o[c]);
      if (l != null && l.references) {
        n = Math.min(n, l.earliestPresentationTime / l.timescale);
        const d = l.references.reduce((h, u) => h + u.info.duration || 0, 0);
        a = Math.max(a, d + l.earliestPresentationTime / l.timescale);
      }
    }
    a && q(a) && Object.keys(i).forEach((c) => {
      i[c].duration || (i[c].duration = a * i[c].timescale - i[c].start);
    });
  }
  return i;
}
function K4(r) {
  const e = {
    valid: null,
    remainder: null
  }, t = pe(r, ["moof"]);
  if (t.length < 2)
    return e.remainder = r, e;
  const i = t[t.length - 1];
  return e.valid = r.slice(0, i.byteOffset - 8), e.remainder = r.slice(i.byteOffset - 8), e;
}
function Qt(r, e) {
  const t = new Uint8Array(r.length + e.length);
  return t.set(r), t.set(e, r.length), t;
}
function jf(r, e) {
  const t = [], i = e.samples, s = e.timescale, n = e.id;
  let a = !1;
  return pe(i, ["moof"]).map((c) => {
    const l = c.byteOffset - 8;
    pe(c, ["traf"]).map((h) => {
      const u = pe(h, ["tfdt"]).map((f) => {
        const p = f[0];
        let m = oe(f, 4);
        return p === 1 && (m *= Math.pow(2, 32), m += oe(f, 8)), m / s;
      })[0];
      return u !== void 0 && (r = u), pe(h, ["tfhd"]).map((f) => {
        const p = oe(f, 4), m = oe(f, 0) & 16777215, g = (m & 1) !== 0, x = (m & 2) !== 0, _ = (m & 8) !== 0;
        let v = 0;
        const E = (m & 16) !== 0;
        let b = 0;
        const A = (m & 32) !== 0;
        let C = 8;
        p === n && (g && (C += 8), x && (C += 4), _ && (v = oe(f, C), C += 4), E && (b = oe(f, C), C += 4), A && (C += 4), e.type === "video" && (a = Ro(e.codec)), pe(h, ["trun"]).map((I) => {
          const L = I[0], R = oe(I, 0) & 16777215, D = (R & 1) !== 0;
          let M = 0;
          const w = (R & 4) !== 0, N = (R & 256) !== 0;
          let H = 0;
          const G = (R & 512) !== 0;
          let Z = 0;
          const $ = (R & 1024) !== 0, Y = (R & 2048) !== 0;
          let W = 0;
          const k = oe(I, 4);
          let P = 8;
          D && (M = oe(I, P), P += 4), w && (P += 4);
          let B = M + l;
          for (let O = 0; O < k; O++) {
            if (N ? (H = oe(I, P), P += 4) : H = v, G ? (Z = oe(I, P), P += 4) : Z = b, $ && (P += 4), Y && (L === 0 ? W = oe(I, P) : W = Kg(I, P), P += 4), e.type === Oe.VIDEO) {
              let j = 0;
              for (; j < Z; ) {
                const Q = oe(i, B);
                if (B += 4, X4(a, i[B])) {
                  const ne = i.subarray(B, B + Q);
                  Ud(ne, a ? 2 : 1, r + W / s, t);
                }
                B += Q, j += Q + 4;
              }
            }
            r += H / s;
          }
        }));
      });
    });
  }), t;
}
function Ro(r) {
  if (!r)
    return !1;
  const e = r.substring(0, 4);
  return e === "hvc1" || e === "hev1" || // Dolby Vision
  e === "dvh1" || e === "dvhe";
}
function X4(r, e) {
  if (r) {
    const t = e >> 1 & 63;
    return t === 39 || t === 40;
  } else
    return (e & 31) === 6;
}
function Ud(r, e, t, i) {
  const s = zg(r);
  let n = 0;
  n += e;
  let a = 0, o = 0, c = 0;
  for (; n < s.length; ) {
    a = 0;
    do {
      if (n >= s.length)
        break;
      c = s[n++], a += c;
    } while (c === 255);
    o = 0;
    do {
      if (n >= s.length)
        break;
      c = s[n++], o += c;
    } while (c === 255);
    const l = s.length - n;
    let d = n;
    if (o < l)
      n += o;
    else if (o > l) {
      Pe.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);
      break;
    }
    if (a === 4) {
      if (s[d++] === 181) {
        const u = $g(s, d);
        if (d += 2, u === 49) {
          const f = oe(s, d);
          if (d += 4, f === 1195456820) {
            const p = s[d++];
            if (p === 3) {
              const m = s[d++], g = 31 & m, x = 64 & m, _ = x ? 2 + g * 3 : 0, v = new Uint8Array(_);
              if (x) {
                v[0] = m;
                for (let E = 1; E < _; E++)
                  v[E] = s[d++];
              }
              i.push({
                type: p,
                payloadType: a,
                pts: t,
                bytes: v
              });
            }
          }
        }
      }
    } else if (a === 5 && o > 16) {
      const h = [];
      for (let p = 0; p < 16; p++) {
        const m = s[d++].toString(16);
        h.push(m.length == 1 ? "0" + m : m), (p === 3 || p === 5 || p === 7 || p === 9) && h.push("-");
      }
      const u = o - 16, f = new Uint8Array(u);
      for (let p = 0; p < u; p++)
        f[p] = s[d++];
      i.push({
        payloadType: a,
        pts: t,
        uuid: h.join(""),
        userData: $t(f),
        userDataBytes: f
      });
    }
  }
}
function zg(r) {
  const e = r.byteLength, t = [];
  let i = 1;
  for (; i < e - 2; )
    r[i] === 0 && r[i + 1] === 0 && r[i + 2] === 3 ? (t.push(i + 2), i += 2) : i++;
  if (t.length === 0)
    return r;
  const s = e - t.length, n = new Uint8Array(s);
  let a = 0;
  for (i = 0; i < s; a++, i++)
    a === t[0] && (a++, t.shift()), n[i] = r[a];
  return n;
}
function Y4(r) {
  const e = r[0];
  let t = "", i = "", s = 0, n = 0, a = 0, o = 0, c = 0, l = 0;
  if (e === 0) {
    for (; st(r.subarray(l, l + 1)) !== "\0"; )
      t += st(r.subarray(l, l + 1)), l += 1;
    for (t += st(r.subarray(l, l + 1)), l += 1; st(r.subarray(l, l + 1)) !== "\0"; )
      i += st(r.subarray(l, l + 1)), l += 1;
    i += st(r.subarray(l, l + 1)), l += 1, s = oe(r, 12), n = oe(r, 16), o = oe(r, 20), c = oe(r, 24), l = 28;
  } else if (e === 1) {
    l += 4, s = oe(r, l), l += 4;
    const h = oe(r, l);
    l += 4;
    const u = oe(r, l);
    for (l += 4, a = 2 ** 32 * h + u, A4(a) || (a = Number.MAX_SAFE_INTEGER, Pe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")), o = oe(r, l), l += 4, c = oe(r, l), l += 4; st(r.subarray(l, l + 1)) !== "\0"; )
      t += st(r.subarray(l, l + 1)), l += 1;
    for (t += st(r.subarray(l, l + 1)), l += 1; st(r.subarray(l, l + 1)) !== "\0"; )
      i += st(r.subarray(l, l + 1)), l += 1;
    i += st(r.subarray(l, l + 1)), l += 1;
  }
  const d = r.subarray(l, r.byteLength);
  return {
    schemeIdUri: t,
    value: i,
    timeScale: s,
    presentationTime: a,
    presentationTimeDelta: n,
    eventDuration: o,
    id: c,
    payload: d
  };
}
function z4(r, ...e) {
  const t = e.length;
  let i = 8, s = t;
  for (; s--; )
    i += e[s].byteLength;
  const n = new Uint8Array(i);
  for (n[0] = i >> 24 & 255, n[1] = i >> 16 & 255, n[2] = i >> 8 & 255, n[3] = i & 255, n.set(r, 4), s = 0, i = 8; s < t; s++)
    n.set(e[s], i), i += e[s].byteLength;
  return n;
}
function j4(r, e, t) {
  if (r.byteLength !== 16)
    throw new RangeError("Invalid system id");
  let i, s;
  i = 0, s = new Uint8Array();
  let n;
  i > 0 ? (n = new Uint8Array(4), e.length > 0 && new DataView(n.buffer).setUint32(0, e.length, !1)) : n = new Uint8Array();
  const a = new Uint8Array(4);
  return t.byteLength > 0 && new DataView(a.buffer).setUint32(0, t.byteLength, !1), z4(
    [112, 115, 115, 104],
    new Uint8Array([
      i,
      0,
      0,
      0
      // Flags
    ]),
    r,
    // 16 bytes
    n,
    s,
    a,
    t
  );
}
const jg = () => /\(Windows.+Firefox\//i.test(navigator.userAgent), kr = {
  audio: {
    a3ds: 1,
    "ac-3": 0.95,
    "ac-4": 1,
    alac: 0.9,
    alaw: 1,
    dra1: 1,
    "dts+": 1,
    "dts-": 1,
    dtsc: 1,
    dtse: 1,
    dtsh: 1,
    "ec-3": 0.9,
    enca: 1,
    fLaC: 0.9,
    // MP4-RA listed codec entry for FLAC
    flac: 0.9,
    // legacy browser codec name for FLAC
    FLAC: 0.9,
    // some manifests may list "FLAC" with Apple's tools
    g719: 1,
    g726: 1,
    m4ae: 1,
    mha1: 1,
    mha2: 1,
    mhm1: 1,
    mhm2: 1,
    mlpa: 1,
    mp4a: 1,
    "raw ": 1,
    Opus: 1,
    opus: 1,
    // browsers expect this to be lowercase despite MP4RA says 'Opus'
    samr: 1,
    sawb: 1,
    sawp: 1,
    sevc: 1,
    sqcp: 1,
    ssmv: 1,
    twos: 1,
    ulaw: 1
  },
  video: {
    avc1: 1,
    avc2: 1,
    avc3: 1,
    avc4: 1,
    avcp: 1,
    av01: 0.8,
    dav1: 0.8,
    drac: 1,
    dva1: 1,
    dvav: 1,
    dvh1: 0.7,
    dvhe: 0.7,
    encv: 1,
    hev1: 0.75,
    hvc1: 0.75,
    mjp2: 1,
    mp4v: 1,
    mvc1: 1,
    mvc2: 1,
    mvc3: 1,
    mvc4: 1,
    resv: 1,
    rv60: 1,
    s263: 1,
    svc1: 1,
    svc2: 1,
    "vc-1": 1,
    vp08: 1,
    vp09: 0.9
  },
  text: {
    stpp: 1,
    wvtt: 1
  }
};
function Vd(r, e) {
  const t = kr[e];
  return !!t && !!t[r.slice(0, 4)];
}
function Lc(r, e, t = !0) {
  return !r.split(",").some((i) => !Wd(i, e, t));
}
function Wd(r, e, t = !0) {
  var i;
  const s = ys(t);
  return (i = s == null ? void 0 : s.isTypeSupported(vn(r, e))) != null ? i : !1;
}
function vn(r, e) {
  return `${e}/mp4;codecs=${r}`;
}
function Qf(r) {
  if (r) {
    const e = r.substring(0, 4);
    return kr.video[e];
  }
  return 2;
}
function eo(r) {
  const e = jg();
  return r.split(",").reduce((t, i) => {
    const n = e && Ro(i) ? 9 : kr.video[i];
    return n ? (n * 2 + t) / (t ? 3 : 2) : (kr.audio[i] + t) / (t ? 2 : 1);
  }, 0);
}
const x0 = {};
function Q4(r, e = !0) {
  if (x0[r])
    return x0[r];
  const t = {
    // Idealy fLaC and Opus would be first (spec-compliant) but
    // some browsers will report that fLaC is supported then fail.
    // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
    flac: ["flac", "fLaC", "FLAC"],
    opus: ["opus", "Opus"],
    // Replace audio codec info if browser does not support mp4a.40.34,
    // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
    "mp4a.40.34": ["mp3"]
  }[r];
  for (let s = 0; s < t.length; s++) {
    var i;
    if (Wd(t[s], "audio", e))
      return x0[r] = t[s], t[s];
    if (t[s] === "mp3" && (i = ys(e)) != null && i.isTypeSupported("audio/mpeg"))
      return "";
  }
  return r;
}
const J4 = /flac|opus|mp4a\.40\.34/i;
function to(r, e = !0) {
  return r.replace(J4, (t) => Q4(t.toLowerCase(), e));
}
function q4(r, e) {
  const t = [];
  if (r) {
    const i = r.split(",");
    for (let s = 0; s < i.length; s++)
      Vd(i[s], "video") || t.push(i[s]);
  }
  return e && t.push(e), t.join(",");
}
function La(r, e) {
  if (r && (r.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(r) !== -1) && (Jf(r, "audio") || Jf(r, "video")))
    return r;
  if (e) {
    const t = e.split(",");
    if (t.length > 1) {
      if (r) {
        for (let i = t.length; i--; )
          if (t[i].substring(0, 4) === r.substring(0, 4))
            return t[i];
      }
      return t[0];
    }
  }
  return e || r;
}
function Jf(r, e) {
  return Vd(r, e) && Wd(r, e);
}
function eC(r) {
  const e = r.split(",");
  for (let t = 0; t < e.length; t++) {
    const i = e[t].split(".");
    i.length > 2 && i[0] === "avc1" && (e[t] = `avc1.${parseInt(i[1]).toString(16)}${("000" + parseInt(i[2]).toString(16)).slice(-4)}`);
  }
  return e.join(",");
}
function tC(r) {
  if (r.startsWith("av01.")) {
    const e = r.split("."), t = ["0", "111", "01", "01", "01", "0"];
    for (let i = e.length; i > 4 && i < 10; i++)
      e[i] = t[i - 4];
    return e.join(".");
  }
  return r;
}
function qf(r) {
  const e = ys(r) || {
    isTypeSupported: () => !1
  };
  return {
    mpeg: e.isTypeSupported("audio/mpeg"),
    mp3: e.isTypeSupported('audio/mp4; codecs="mp3"'),
    ac3: e.isTypeSupported('audio/mp4; codecs="ac-3"')
  };
}
function Dc(r) {
  return r.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
}
const iC = {
  supported: !0,
  powerEfficient: !0,
  smooth: !0
  // keySystemAccess: null,
}, sC = {
  supported: !1,
  smooth: !1,
  powerEfficient: !1
  // keySystemAccess: null,
}, Qg = {
  supported: !0,
  configurations: [],
  decodingInfoResults: [iC]
};
function Jg(r, e) {
  return {
    supported: !1,
    configurations: e,
    decodingInfoResults: [sC],
    error: r
  };
}
function rC(r, e, t, i, s, n) {
  const a = r.videoCodec, o = r.audioCodec ? r.audioGroups : null, c = n == null ? void 0 : n.audioCodec, l = n == null ? void 0 : n.channels, d = l ? parseInt(l) : c ? 1 / 0 : 2;
  let h = null;
  if (o != null && o.length)
    try {
      o.length === 1 && o[0] ? h = e.groups[o[0]].channels : h = o.reduce((u, f) => {
        if (f) {
          const p = e.groups[f];
          if (!p)
            throw new Error(`Audio track group ${f} not found`);
          Object.keys(p.channels).forEach((m) => {
            u[m] = (u[m] || 0) + p.channels[m];
          });
        }
        return u;
      }, {
        2: 0
      });
    } catch {
      return !0;
    }
  return a !== void 0 && // Force media capabilities check for HEVC to avoid failure on Windows
  (a.split(",").some((u) => Ro(u)) || r.width > 1920 && r.height > 1088 || r.height > 1920 && r.width > 1088 || r.frameRate > Math.max(i, 30) || r.videoRange !== "SDR" && r.videoRange !== t || r.bitrate > Math.max(s, 8e6)) || !!h && q(d) && Object.keys(h).some((u) => parseInt(u) > d);
}
function qg(r, e, t, i = {}) {
  const s = r.videoCodec;
  if (!s && !r.audioCodec || !t)
    return Promise.resolve(Qg);
  const n = [], a = nC(r), o = a.length, c = aC(r, e, o > 0), l = c.length;
  for (let d = o || 1 * l || 1; d--; ) {
    const h = {
      type: "media-source"
    };
    if (o && (h.video = a[d % o]), l) {
      h.audio = c[d % l];
      const u = h.audio.bitrate;
      h.video && u && (h.video.bitrate -= u);
    }
    n.push(h);
  }
  if (s) {
    const d = navigator.userAgent;
    if (s.split(",").some((h) => Ro(h)) && jg())
      return Promise.resolve(Jg(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`), n));
  }
  return Promise.all(n.map((d) => {
    const h = lC(d);
    return i[h] || (i[h] = t.decodingInfo(d));
  })).then((d) => ({
    supported: !d.some((h) => !h.supported),
    configurations: n,
    decodingInfoResults: d
  })).catch((d) => ({
    supported: !1,
    configurations: n,
    decodingInfoResults: [],
    error: d
  }));
}
function nC(r) {
  var e;
  const t = (e = r.videoCodec) == null ? void 0 : e.split(","), i = e_(r), s = r.width || 640, n = r.height || 480, a = r.frameRate || 30, o = r.videoRange.toLowerCase();
  return t ? t.map((c) => {
    const l = {
      contentType: vn(tC(c), "video"),
      width: s,
      height: n,
      bitrate: i,
      framerate: a
    };
    return o !== "sdr" && (l.transferFunction = o), l;
  }) : [];
}
function aC(r, e, t) {
  var i;
  const s = (i = r.audioCodec) == null ? void 0 : i.split(","), n = e_(r);
  return s && r.audioGroups ? r.audioGroups.reduce((a, o) => {
    var c;
    const l = o ? (c = e.groups[o]) == null ? void 0 : c.tracks : null;
    return l ? l.reduce((d, h) => {
      if (h.groupId === o) {
        const u = parseFloat(h.channels || "");
        s.forEach((f) => {
          const p = {
            contentType: vn(f, "audio"),
            bitrate: t ? oC(f, n) : n
          };
          u && (p.channels = "" + u), d.push(p);
        });
      }
      return d;
    }, a) : a;
  }, []) : [];
}
function oC(r, e) {
  if (e <= 1)
    return 1;
  let t = 128e3;
  return r === "ec-3" ? t = 768e3 : r === "ac-3" && (t = 64e4), Math.min(e / 2, t);
}
function e_(r) {
  return Math.ceil(Math.max(r.bitrate * 0.9, r.averageBitrate) / 1e3) * 1e3 || 1;
}
function lC(r) {
  let e = "";
  const {
    audio: t,
    video: i
  } = r;
  if (i) {
    const s = Dc(i.contentType);
    e += `${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction || "sd"}_${Math.ceil(i.bitrate / 1e5)}`;
  }
  if (t) {
    const s = Dc(t.contentType);
    e += `${i ? "_" : ""}${s}_c${t.channels}`;
  }
  return e;
}
const Pc = ["NONE", "TYPE-0", "TYPE-1", null];
function cC(r) {
  return Pc.indexOf(r) > -1;
}
const io = ["SDR", "PQ", "HLG"];
function dC(r) {
  return !!r && io.indexOf(r) > -1;
}
var Da = {
  No: "",
  Yes: "YES",
  v2: "v2"
};
function ep(r) {
  const {
    canSkipUntil: e,
    canSkipDateRanges: t,
    age: i
  } = r, s = i < e / 2;
  return e && s ? t ? Da.v2 : Da.Yes : Da.No;
}
class tp {
  constructor(e, t, i) {
    this.msn = void 0, this.part = void 0, this.skip = void 0, this.msn = e, this.part = t, this.skip = i;
  }
  addDirectives(e) {
    const t = new self.URL(e);
    return this.msn !== void 0 && t.searchParams.set("_HLS_msn", this.msn.toString()), this.part !== void 0 && t.searchParams.set("_HLS_part", this.part.toString()), this.skip && t.searchParams.set("_HLS_skip", this.skip), t.href;
  }
}
class En {
  constructor(e) {
    if (this._attrs = void 0, this.audioCodec = void 0, this.bitrate = void 0, this.codecSet = void 0, this.url = void 0, this.frameRate = void 0, this.height = void 0, this.id = void 0, this.name = void 0, this.supplemental = void 0, this.videoCodec = void 0, this.width = void 0, this.details = void 0, this.fragmentError = 0, this.loadError = 0, this.loaded = void 0, this.realBitrate = 0, this.supportedPromise = void 0, this.supportedResult = void 0, this._avgBitrate = 0, this._audioGroups = void 0, this._subtitleGroups = void 0, this._urlId = 0, this.url = [e.url], this._attrs = [e.attrs], this.bitrate = e.bitrate, e.details && (this.details = e.details), this.id = e.id || 0, this.name = e.name, this.width = e.width || 0, this.height = e.height || 0, this.frameRate = e.attrs.optionalFloat("FRAME-RATE", 0), this._avgBitrate = e.attrs.decimalInteger("AVERAGE-BANDWIDTH"), this.audioCodec = e.audioCodec, this.videoCodec = e.videoCodec, this.codecSet = [e.videoCodec, e.audioCodec].filter((i) => !!i).map((i) => i.substring(0, 4)).join(","), "supplemental" in e) {
      var t;
      this.supplemental = e.supplemental;
      const i = (t = e.supplemental) == null ? void 0 : t.videoCodec;
      i && i !== e.videoCodec && (this.codecSet += `,${i.substring(0, 4)}`);
    }
    this.addGroupId("audio", e.attrs.AUDIO), this.addGroupId("text", e.attrs.SUBTITLES);
  }
  get maxBitrate() {
    return Math.max(this.realBitrate, this.bitrate);
  }
  get averageBitrate() {
    return this._avgBitrate || this.realBitrate || this.bitrate;
  }
  get attrs() {
    return this._attrs[0];
  }
  get codecs() {
    return this.attrs.CODECS || "";
  }
  get pathwayId() {
    return this.attrs["PATHWAY-ID"] || ".";
  }
  get videoRange() {
    return this.attrs["VIDEO-RANGE"] || "SDR";
  }
  get score() {
    return this.attrs.optionalFloat("SCORE", 0);
  }
  get uri() {
    return this.url[0] || "";
  }
  hasAudioGroup(e) {
    return ip(this._audioGroups, e);
  }
  hasSubtitleGroup(e) {
    return ip(this._subtitleGroups, e);
  }
  get audioGroups() {
    return this._audioGroups;
  }
  get subtitleGroups() {
    return this._subtitleGroups;
  }
  addGroupId(e, t) {
    if (t) {
      if (e === "audio") {
        let i = this._audioGroups;
        i || (i = this._audioGroups = []), i.indexOf(t) === -1 && i.push(t);
      } else if (e === "text") {
        let i = this._subtitleGroups;
        i || (i = this._subtitleGroups = []), i.indexOf(t) === -1 && i.push(t);
      }
    }
  }
  // Deprecated methods (retained for backwards compatibility)
  get urlId() {
    return 0;
  }
  set urlId(e) {
  }
  get audioGroupIds() {
    return this.audioGroups ? [this.audioGroupId] : void 0;
  }
  get textGroupIds() {
    return this.subtitleGroups ? [this.textGroupId] : void 0;
  }
  get audioGroupId() {
    var e;
    return (e = this.audioGroups) == null ? void 0 : e[0];
  }
  get textGroupId() {
    var e;
    return (e = this.subtitleGroups) == null ? void 0 : e[0];
  }
  addFallback() {
  }
}
function ip(r, e) {
  return !e || !r ? !1 : r.indexOf(e) !== -1;
}
function hC() {
  if (typeof matchMedia == "function") {
    const r = matchMedia("(dynamic-range: high)"), e = matchMedia("bad query");
    if (r.media !== e.media)
      return r.matches === !0;
  }
  return !1;
}
function uC(r, e) {
  let t = !1, i = [];
  if (r && (t = r !== "SDR", i = [r]), e) {
    i = e.allowedVideoRanges || io.slice(0);
    const s = i.join("") !== "SDR" && !e.videoCodec;
    t = e.preferHDR !== void 0 ? e.preferHDR : s && hC(), t || (i = ["SDR"]);
  }
  return {
    preferHDR: t,
    allowedVideoRanges: i
  };
}
const fC = (r) => {
  const e = /* @__PURE__ */ new WeakSet();
  return (t, i) => {
    if (r && (i = r(t, i)), typeof i == "object" && i !== null) {
      if (e.has(i))
        return;
      e.add(i);
    }
    return i;
  };
}, Ze = (r, e) => JSON.stringify(r, fC(e));
function pC(r, e, t, i, s) {
  const n = Object.keys(r), a = i == null ? void 0 : i.channels, o = i == null ? void 0 : i.audioCodec, c = s == null ? void 0 : s.videoCodec, l = a && parseInt(a) === 2;
  let d = !1, h = !1, u = 1 / 0, f = 1 / 0, p = 1 / 0, m = 1 / 0, g = 0, x = [];
  const {
    preferHDR: _,
    allowedVideoRanges: v
  } = uC(e, s);
  for (let I = n.length; I--; ) {
    const L = r[n[I]];
    d || (d = L.channels[2] > 0), u = Math.min(u, L.minHeight), f = Math.min(f, L.minFramerate), p = Math.min(p, L.minBitrate), v.filter((D) => L.videoRanges[D] > 0).length > 0 && (h = !0);
  }
  u = q(u) ? u : 0, f = q(f) ? f : 0;
  const E = Math.max(1080, u), b = Math.max(30, f);
  p = q(p) ? p : t, t = Math.max(p, t), h || (e = void 0);
  const A = n.length > 1;
  return {
    codecSet: n.reduce((I, L) => {
      const R = r[L];
      if (L === I)
        return I;
      if (x = h ? v.filter((D) => R.videoRanges[D] > 0) : [], A) {
        if (R.minBitrate > t)
          return xi(L, `min bitrate of ${R.minBitrate} > current estimate of ${t}`), I;
        if (!R.hasDefaultAudio)
          return xi(L, "no renditions with default or auto-select sound found"), I;
        if (o && L.indexOf(o.substring(0, 4)) % 5 !== 0)
          return xi(L, `audio codec preference "${o}" not found`), I;
        if (a && !l) {
          if (!R.channels[a])
            return xi(L, `no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`), I;
        } else if ((!o || l) && d && R.channels[2] === 0)
          return xi(L, "no renditions with stereo sound found"), I;
        if (R.minHeight > E)
          return xi(L, `min resolution of ${R.minHeight} > maximum of ${E}`), I;
        if (R.minFramerate > b)
          return xi(L, `min framerate of ${R.minFramerate} > maximum of ${b}`), I;
        if (!x.some((D) => R.videoRanges[D] > 0))
          return xi(L, `no variants with VIDEO-RANGE of ${Ze(x)} found`), I;
        if (c && L.indexOf(c.substring(0, 4)) % 5 !== 0)
          return xi(L, `video codec preference "${c}" not found`), I;
        if (R.maxScore < g)
          return xi(L, `max score of ${R.maxScore} < selected max of ${g}`), I;
      }
      return I && (eo(L) >= eo(I) || R.fragmentError > r[I].fragmentError) ? I : (m = R.minIndex, g = R.maxScore, L);
    }, void 0),
    videoRanges: x,
    preferHDR: _,
    minFramerate: f,
    minBitrate: p,
    minIndex: m
  };
}
function xi(r, e) {
  Pe.log(`[abr] start candidates with "${r}" ignored because ${e}`);
}
function t_(r) {
  return r.reduce((e, t) => {
    let i = e.groups[t.groupId];
    i || (i = e.groups[t.groupId] = {
      tracks: [],
      channels: {
        2: 0
      },
      hasDefault: !1,
      hasAutoSelect: !1
    }), i.tracks.push(t);
    const s = t.channels || "2";
    return i.channels[s] = (i.channels[s] || 0) + 1, i.hasDefault = i.hasDefault || t.default, i.hasAutoSelect = i.hasAutoSelect || t.autoselect, i.hasDefault && (e.hasDefaultAudio = !0), i.hasAutoSelect && (e.hasAutoSelectAudio = !0), e;
  }, {
    hasDefaultAudio: !1,
    hasAutoSelectAudio: !1,
    groups: {}
  });
}
function mC(r, e, t, i) {
  return r.slice(t, i + 1).reduce((s, n, a) => {
    if (!n.codecSet)
      return s;
    const o = n.audioGroups;
    let c = s[n.codecSet];
    c || (s[n.codecSet] = c = {
      minBitrate: 1 / 0,
      minHeight: 1 / 0,
      minFramerate: 1 / 0,
      minIndex: a,
      maxScore: 0,
      videoRanges: {
        SDR: 0
      },
      channels: {
        2: 0
      },
      hasDefaultAudio: !o,
      fragmentError: 0
    }), c.minBitrate = Math.min(c.minBitrate, n.bitrate);
    const l = Math.min(n.height, n.width);
    return c.minHeight = Math.min(c.minHeight, l), c.minFramerate = Math.min(c.minFramerate, n.frameRate), c.minIndex = Math.min(c.minIndex, a), c.maxScore = Math.max(c.maxScore, n.score), c.fragmentError += n.fragmentError, c.videoRanges[n.videoRange] = (c.videoRanges[n.videoRange] || 0) + 1, o && o.forEach((d) => {
      if (!d)
        return;
      const h = e.groups[d];
      h && (c.hasDefaultAudio = c.hasDefaultAudio || e.hasDefaultAudio ? h.hasDefault : h.hasAutoSelect || !e.hasDefaultAudio && !e.hasAutoSelectAudio, Object.keys(h.channels).forEach((u) => {
        c.channels[u] = (c.channels[u] || 0) + h.channels[u];
      }));
    }), s;
  }, {});
}
function sp(r) {
  if (!r)
    return r;
  const {
    lang: e,
    assocLang: t,
    characteristics: i,
    channels: s,
    audioCodec: n
  } = r;
  return {
    lang: e,
    assocLang: t,
    characteristics: i,
    channels: s,
    audioCodec: n
  };
}
function Di(r, e, t) {
  if ("attrs" in r) {
    const i = e.indexOf(r);
    if (i !== -1)
      return i;
  }
  for (let i = 0; i < e.length; i++) {
    const s = e[i];
    if (Bs(r, s, t))
      return i;
  }
  return -1;
}
function Bs(r, e, t) {
  const {
    groupId: i,
    name: s,
    lang: n,
    assocLang: a,
    default: o
  } = r, c = r.forced;
  return (i === void 0 || e.groupId === i) && (s === void 0 || e.name === s) && (n === void 0 || gC(n, e.lang)) && (n === void 0 || e.assocLang === a) && (o === void 0 || e.default === o) && (c === void 0 || e.forced === c) && (!("characteristics" in r) || _C(r.characteristics || "", e.characteristics)) && (t === void 0 || t(r, e));
}
function gC(r, e = "--") {
  return r.length === e.length ? r === e : r.startsWith(e) || e.startsWith(r);
}
function _C(r, e = "") {
  const t = r.split(","), i = e.split(",");
  return t.length === i.length && !t.some((s) => i.indexOf(s) === -1);
}
function Ls(r, e) {
  const {
    audioCodec: t,
    channels: i
  } = r;
  return (t === void 0 || (e.audioCodec || "").substring(0, 4) === t.substring(0, 4)) && (i === void 0 || i === (e.channels || "2"));
}
function yC(r, e, t, i, s) {
  const n = e[i], o = e.reduce((u, f, p) => {
    const m = f.uri;
    return (u[m] || (u[m] = [])).push(p), u;
  }, {})[n.uri];
  o.length > 1 && (i = Math.max.apply(Math, o));
  const c = n.videoRange, l = n.frameRate, d = n.codecSet.substring(0, 4), h = rp(e, i, (u) => {
    if (u.videoRange !== c || u.frameRate !== l || u.codecSet.substring(0, 4) !== d)
      return !1;
    const f = u.audioGroups, p = t.filter((m) => !f || f.indexOf(m.groupId) !== -1);
    return Di(r, p, s) > -1;
  });
  return h > -1 ? h : rp(e, i, (u) => {
    const f = u.audioGroups, p = t.filter((m) => !f || f.indexOf(m.groupId) !== -1);
    return Di(r, p, s) > -1;
  });
}
function rp(r, e, t) {
  for (let i = e; i > -1; i--)
    if (t(r[i]))
      return i;
  for (let i = e + 1; i < r.length; i++)
    if (t(r[i]))
      return i;
  return -1;
}
function so(r, e) {
  var t;
  return !!r && r !== ((t = e.loadLevelObj) == null ? void 0 : t.uri);
}
class xC extends qt {
  constructor(e) {
    super("abr", e.logger), this.hls = void 0, this.lastLevelLoadSec = 0, this.lastLoadedFragLevel = -1, this.firstSelection = -1, this._nextAutoLevel = -1, this.nextAutoLevelKey = "", this.audioTracksByGroup = null, this.codecTiers = null, this.timer = -1, this.fragCurrent = null, this.partCurrent = null, this.bitrateTestDelay = 0, this.rebufferNotice = -1, this.supportedCache = {}, this.bwEstimator = void 0, this._abandonRulesCheck = (t) => {
      var i;
      const {
        fragCurrent: s,
        partCurrent: n,
        hls: a
      } = this, {
        autoLevelEnabled: o,
        media: c
      } = a;
      if (!s || !c)
        return;
      const l = performance.now(), d = n ? n.stats : s.stats, h = n ? n.duration : s.duration, u = l - d.loading.start, f = a.minAutoLevel, p = s.level, m = this._nextAutoLevel;
      if (d.aborted || d.loaded && d.loaded === d.total || p <= f) {
        this.clearTimer(), this._nextAutoLevel = -1;
        return;
      }
      if (!o)
        return;
      const g = m > -1 && m !== p, x = !!t || g;
      if (!x && (c.paused || !c.playbackRate || !c.readyState))
        return;
      const _ = a.mainForwardBufferInfo;
      if (!x && _ === null)
        return;
      const v = this.bwEstimator.getEstimateTTFB(), E = Math.abs(c.playbackRate);
      if (u <= Math.max(v, 1e3 * (h / (E * 2))))
        return;
      const b = _ ? _.len / E : 0, A = d.loading.first ? d.loading.first - d.loading.start : -1, C = d.loaded && A > -1, I = this.getBwEstimate(), L = a.levels, R = L[p], D = Math.max(d.loaded, Math.round(h * (s.bitrate || R.averageBitrate) / 8));
      let M = C ? u - A : u;
      M < 1 && C && (M = Math.min(u, d.loaded * 8 / I));
      const w = C ? d.loaded * 1e3 / M : 0, N = v / 1e3, H = w ? (D - d.loaded) / w : D * 8 / I + N;
      if (H <= b)
        return;
      const G = w ? w * 8 : I, Z = ((i = (t == null ? void 0 : t.details) || this.hls.latestLevelDetails) == null ? void 0 : i.live) === !0, $ = this.hls.config.abrBandWidthUpFactor;
      let Y = Number.POSITIVE_INFINITY, W;
      for (W = p - 1; W > f; W--) {
        const O = L[W].maxBitrate, j = !L[W].details || Z;
        if (Y = this.getTimeToLoadFrag(N, G, h * O, j), Y < Math.min(b, h + N))
          break;
      }
      if (Y >= H || Y > h * 10)
        return;
      C ? this.bwEstimator.sample(u - Math.min(v, A), d.loaded) : this.bwEstimator.sampleTTFB(u);
      const k = L[W].maxBitrate;
      this.getBwEstimate() * $ > k && this.resetEstimator(k);
      const P = this.findBestLevel(k, f, W, 0, b, 1, 1);
      P > -1 && (W = P), this.warn(`Fragment ${s.sn}${n ? " part " + n.index : ""} of level ${p} is loading too slowly;
      Fragment duration: ${s.duration.toFixed(3)}
      Time to underbuffer: ${b.toFixed(3)} s
      Estimated load time for current fragment: ${H.toFixed(3)} s
      Estimated load time for down switch fragment: ${Y.toFixed(3)} s
      TTFB estimate: ${A | 0} ms
      Current BW estimate: ${q(I) ? I | 0 : "Unknown"} bps
      New BW estimate: ${this.getBwEstimate() | 0} bps
      Switching to level ${W} @ ${k | 0} bps`), a.nextLoadLevel = a.nextAutoLevel = W, this.clearTimer();
      const B = () => {
        if (this.clearTimer(), this.fragCurrent === s && this.hls.loadLevel === W && W > 0) {
          const O = this.getStarvationDelay();
          if (this.warn(`Aborting inflight request ${W > 0 ? "and switching down" : ""}
      Fragment duration: ${s.duration.toFixed(3)} s
      Time to underbuffer: ${O.toFixed(3)} s`), s.abortRequests(), this.fragCurrent = this.partCurrent = null, W > f) {
            let j = this.findBestLevel(this.hls.levels[f].bitrate, f, W, 0, O, 1, 1);
            j === -1 && (j = f), this.hls.nextLoadLevel = this.hls.nextAutoLevel = j, this.resetEstimator(this.hls.levels[j].bitrate);
          }
        }
      };
      g || H > Y * 2 ? B() : this.timer = self.setInterval(B, Y * 1e3), a.trigger(T.FRAG_LOAD_EMERGENCY_ABORTED, {
        frag: s,
        part: n,
        stats: d
      });
    }, this.hls = e, this.bwEstimator = this.initEstimator(), this.registerListeners();
  }
  resetEstimator(e) {
    e && (this.log(`setting initial bwe to ${e}`), this.hls.config.abrEwmaDefaultEstimate = e), this.firstSelection = -1, this.bwEstimator = this.initEstimator();
  }
  initEstimator() {
    const e = this.hls.config;
    return new R4(e.abrEwmaSlowVoD, e.abrEwmaFastVoD, e.abrEwmaDefaultEstimate);
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.FRAG_LOADING, this.onFragLoading, this), e.on(T.FRAG_LOADED, this.onFragLoaded, this), e.on(T.FRAG_BUFFERED, this.onFragBuffered, this), e.on(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.on(T.LEVEL_LOADED, this.onLevelLoaded, this), e.on(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.on(T.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.FRAG_LOADING, this.onFragLoading, this), e.off(T.FRAG_LOADED, this.onFragLoaded, this), e.off(T.FRAG_BUFFERED, this.onFragBuffered, this), e.off(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.off(T.LEVEL_LOADED, this.onLevelLoaded, this), e.off(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.off(T.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this), e.off(T.ERROR, this.onError, this));
  }
  destroy() {
    this.unregisterListeners(), this.clearTimer(), this.hls = this._abandonRulesCheck = this.supportedCache = null, this.fragCurrent = this.partCurrent = null;
  }
  onManifestLoading(e, t) {
    this.lastLoadedFragLevel = -1, this.firstSelection = -1, this.lastLevelLoadSec = 0, this.supportedCache = {}, this.fragCurrent = this.partCurrent = null, this.onLevelsUpdated(), this.clearTimer();
  }
  onLevelsUpdated() {
    this.lastLoadedFragLevel > -1 && this.fragCurrent && (this.lastLoadedFragLevel = this.fragCurrent.level), this._nextAutoLevel = -1, this.onMaxAutoLevelUpdated(), this.codecTiers = null, this.audioTracksByGroup = null;
  }
  onMaxAutoLevelUpdated() {
    this.firstSelection = -1, this.nextAutoLevelKey = "";
  }
  onFragLoading(e, t) {
    const i = t.frag;
    if (!this.ignoreFragment(i)) {
      if (!i.bitrateTest) {
        var s;
        this.fragCurrent = i, this.partCurrent = (s = t.part) != null ? s : null;
      }
      this.clearTimer(), this.timer = self.setInterval(this._abandonRulesCheck, 100);
    }
  }
  onLevelSwitching(e, t) {
    this.clearTimer();
  }
  onError(e, t) {
    if (!t.fatal)
      switch (t.details) {
        case V.BUFFER_ADD_CODEC_ERROR:
        case V.BUFFER_APPEND_ERROR:
          this.lastLoadedFragLevel = -1, this.firstSelection = -1;
          break;
        case V.FRAG_LOAD_TIMEOUT: {
          const i = t.frag, {
            fragCurrent: s,
            partCurrent: n
          } = this;
          if (i && s && i.sn === s.sn && i.level === s.level) {
            const a = performance.now(), o = n ? n.stats : i.stats, c = a - o.loading.start, l = o.loading.first ? o.loading.first - o.loading.start : -1;
            if (o.loaded && l > -1) {
              const h = this.bwEstimator.getEstimateTTFB();
              this.bwEstimator.sample(c - Math.min(h, l), o.loaded);
            } else
              this.bwEstimator.sampleTTFB(c);
          }
          break;
        }
      }
  }
  getTimeToLoadFrag(e, t, i, s) {
    const n = e + i / t, a = s ? e + this.lastLevelLoadSec : 0;
    return n + a;
  }
  onLevelLoaded(e, t) {
    const i = this.hls.config, {
      loading: s
    } = t.stats, n = s.end - s.first;
    q(n) && (this.lastLevelLoadSec = n / 1e3), t.details.live ? this.bwEstimator.update(i.abrEwmaSlowLive, i.abrEwmaFastLive) : this.bwEstimator.update(i.abrEwmaSlowVoD, i.abrEwmaFastVoD), this.timer > -1 && this._abandonRulesCheck(t.levelInfo);
  }
  onFragLoaded(e, {
    frag: t,
    part: i
  }) {
    const s = i ? i.stats : t.stats;
    if (t.type === te.MAIN && this.bwEstimator.sampleTTFB(s.loading.first - s.loading.start), !this.ignoreFragment(t)) {
      if (this.clearTimer(), t.level === this._nextAutoLevel && (this._nextAutoLevel = -1), this.firstSelection = -1, this.hls.config.abrMaxWithRealBitrate) {
        const n = i ? i.duration : t.duration, a = this.hls.levels[t.level], o = (a.loaded ? a.loaded.bytes : 0) + s.loaded, c = (a.loaded ? a.loaded.duration : 0) + n;
        a.loaded = {
          bytes: o,
          duration: c
        }, a.realBitrate = Math.round(8 * o / c);
      }
      if (t.bitrateTest) {
        const n = {
          stats: s,
          frag: t,
          part: i,
          id: t.type
        };
        this.onFragBuffered(T.FRAG_BUFFERED, n), t.bitrateTest = !1;
      } else
        this.lastLoadedFragLevel = t.level;
    }
  }
  onFragBuffered(e, t) {
    const {
      frag: i,
      part: s
    } = t, n = s != null && s.stats.loaded ? s.stats : i.stats;
    if (n.aborted || this.ignoreFragment(i))
      return;
    const a = n.parsing.end - n.loading.start - Math.min(n.loading.first - n.loading.start, this.bwEstimator.getEstimateTTFB());
    this.bwEstimator.sample(a, n.loaded), n.bwEstimate = this.getBwEstimate(), i.bitrateTest ? this.bitrateTestDelay = a / 1e3 : this.bitrateTestDelay = 0;
  }
  ignoreFragment(e) {
    return e.type !== te.MAIN || e.sn === "initSegment";
  }
  clearTimer() {
    this.timer > -1 && (self.clearInterval(this.timer), this.timer = -1);
  }
  get firstAutoLevel() {
    const {
      maxAutoLevel: e,
      minAutoLevel: t
    } = this.hls, i = this.getBwEstimate(), s = this.hls.config.maxStarvationDelay, n = this.findBestLevel(i, t, e, 0, s, 1, 1);
    if (n > -1)
      return n;
    const a = this.hls.firstLevel, o = Math.min(Math.max(a, t), e);
    return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`), o;
  }
  get forcedAutoLevel() {
    return this.nextAutoLevelKey ? -1 : this._nextAutoLevel;
  }
  // return next auto level
  get nextAutoLevel() {
    const e = this.forcedAutoLevel, i = this.bwEstimator.canEstimate(), s = this.lastLoadedFragLevel > -1;
    if (e !== -1 && (!i || !s || this.nextAutoLevelKey === this.getAutoLevelKey()))
      return e;
    const n = i && s ? this.getNextABRAutoLevel() : this.firstAutoLevel;
    if (e !== -1) {
      const a = this.hls.levels;
      if (a.length > Math.max(e, n) && a[e].loadError <= a[n].loadError)
        return e;
    }
    return this._nextAutoLevel = n, this.nextAutoLevelKey = this.getAutoLevelKey(), n;
  }
  getAutoLevelKey() {
    return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  }
  getNextABRAutoLevel() {
    const {
      fragCurrent: e,
      partCurrent: t,
      hls: i
    } = this;
    if (i.levels.length <= 1)
      return i.loadLevel;
    const {
      maxAutoLevel: s,
      config: n,
      minAutoLevel: a
    } = i, o = t ? t.duration : e ? e.duration : 0, c = this.getBwEstimate(), l = this.getStarvationDelay();
    let d = n.abrBandWidthFactor, h = n.abrBandWidthUpFactor;
    if (l) {
      const g = this.findBestLevel(c, a, s, l, 0, d, h);
      if (g >= 0)
        return this.rebufferNotice = -1, g;
    }
    let u = o ? Math.min(o, n.maxStarvationDelay) : n.maxStarvationDelay;
    if (!l) {
      const g = this.bitrateTestDelay;
      g && (u = (o ? Math.min(o, n.maxLoadingDelay) : n.maxLoadingDelay) - g, this.info(`bitrate test took ${Math.round(1e3 * g)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * u)} ms`), d = h = 1);
    }
    const f = this.findBestLevel(c, a, s, l, u, d, h);
    if (this.rebufferNotice !== f && (this.rebufferNotice = f, this.info(`${l ? "rebuffering expected" : "buffer is empty"}, optimal quality level ${f}`)), f > -1)
      return f;
    const p = i.levels[a], m = i.loadLevelObj;
    return m && (p == null ? void 0 : p.bitrate) < m.bitrate ? a : i.loadLevel;
  }
  getStarvationDelay() {
    const e = this.hls, t = e.media;
    if (!t)
      return 1 / 0;
    const i = t && t.playbackRate !== 0 ? Math.abs(t.playbackRate) : 1, s = e.mainForwardBufferInfo;
    return (s ? s.len : 0) / i;
  }
  getBwEstimate() {
    return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  }
  findBestLevel(e, t, i, s, n, a, o) {
    var c;
    const l = s + n, d = this.lastLoadedFragLevel, h = d === -1 ? this.hls.firstLevel : d, {
      fragCurrent: u,
      partCurrent: f
    } = this, {
      levels: p,
      allAudioTracks: m,
      loadLevel: g,
      config: x
    } = this.hls;
    if (p.length === 1)
      return 0;
    const _ = p[h], v = !!((c = this.hls.latestLevelDetails) != null && c.live), E = g === -1 || d === -1;
    let b, A = "SDR", C = (_ == null ? void 0 : _.frameRate) || 0;
    const {
      audioPreference: I,
      videoPreference: L
    } = x, R = this.audioTracksByGroup || (this.audioTracksByGroup = t_(m));
    let D = -1;
    if (E) {
      if (this.firstSelection !== -1)
        return this.firstSelection;
      const G = this.codecTiers || (this.codecTiers = mC(p, R, t, i)), Z = pC(G, A, e, I, L), {
        codecSet: $,
        videoRanges: Y,
        minFramerate: W,
        minBitrate: k,
        minIndex: P,
        preferHDR: B
      } = Z;
      D = P, b = $, A = B ? Y[Y.length - 1] : Y[0], C = W, e = Math.max(e, k), this.log(`picked start tier ${Ze(Z)}`);
    } else
      b = _ == null ? void 0 : _.codecSet, A = _ == null ? void 0 : _.videoRange;
    const M = f ? f.duration : u ? u.duration : 0, w = this.bwEstimator.getEstimateTTFB() / 1e3, N = [];
    for (let G = i; G >= t; G--) {
      var H;
      const Z = p[G], $ = G > h;
      if (!Z)
        continue;
      if (x.useMediaCapabilities && !Z.supportedResult && !Z.supportedPromise) {
        const j = navigator.mediaCapabilities;
        typeof (j == null ? void 0 : j.decodingInfo) == "function" && rC(Z, R, A, C, e, I) ? (Z.supportedPromise = qg(Z, R, j, this.supportedCache), Z.supportedPromise.then((Q) => {
          if (!this.hls)
            return;
          Z.supportedResult = Q;
          const ne = this.hls.levels, J = ne.indexOf(Z);
          Q.error ? this.warn(`MediaCapabilities decodingInfo error: "${Q.error}" for level ${J} ${Ze(Q)}`) : Q.supported ? Q.decodingInfoResults.some((Se) => Se.smooth === !1 || Se.powerEfficient === !1) && this.log(`MediaCapabilities decodingInfo for level ${J} not smooth or powerEfficient: ${Ze(Q)}`) : (this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${J} ${Ze(Q)}`), J > -1 && ne.length > 1 && (this.log(`Removing unsupported level ${J}`), this.hls.removeLevel(J), this.hls.loadLevel === -1 && (this.hls.nextLoadLevel = 0)));
        }).catch((Q) => {
          this.warn(`Error handling MediaCapabilities decodingInfo: ${Q}`);
        })) : Z.supportedResult = Qg;
      }
      if ((b && Z.codecSet !== b || A && Z.videoRange !== A || $ && C > Z.frameRate || !$ && C > 0 && C < Z.frameRate || (H = Z.supportedResult) != null && (H = H.decodingInfoResults) != null && H.some((j) => j.smooth === !1)) && (!E || G !== D)) {
        N.push(G);
        continue;
      }
      const Y = Z.details, W = (f ? Y == null ? void 0 : Y.partTarget : Y == null ? void 0 : Y.averagetargetduration) || M;
      let k;
      $ ? k = o * e : k = a * e;
      const P = M && s >= M * 2 && n === 0 ? Z.averageBitrate : Z.maxBitrate, B = this.getTimeToLoadFrag(w, k, P * W, Y === void 0);
      if (
        // if adjusted bw is greater than level bitrate AND
        k >= P && // no level change, or new level has no error history
        (G === d || Z.loadError === 0 && Z.fragmentError === 0) && // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
        // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
        // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
        (B <= w || !q(B) || v && !this.bitrateTestDelay || B < l)
      ) {
        const j = this.forcedAutoLevel;
        return G !== g && (j === -1 || j !== g) && (N.length && this.trace(`Skipped level(s) ${N.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${p[N[0]].codecs}" ${p[N[0]].videoRange}; not compatible with "${b}" ${A}`), this.info(`switch candidate:${h}->${G} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k - P)} ttfb:${w.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${B.toFixed(1)} firstSelection:${E} codecSet:${Z.codecSet} videoRange:${Z.videoRange} hls.loadLevel:${g}`)), E && (this.firstSelection = G), G;
      }
    }
    return -1;
  }
  set nextAutoLevel(e) {
    const t = this.deriveNextAutoLevel(e);
    this._nextAutoLevel !== t && (this.nextAutoLevelKey = "", this._nextAutoLevel = t);
  }
  deriveNextAutoLevel(e) {
    const {
      maxAutoLevel: t,
      minAutoLevel: i
    } = this.hls;
    return Math.min(Math.max(e, i), t);
  }
}
const i_ = {
  /**
   * Searches for an item in an array which matches a certain condition.
   * This requires the condition to only match one item in the array,
   * and for the array to be ordered.
   *
   * @param list The array to search.
   * @param comparisonFn
   *      Called and provided a candidate item as the first argument.
   *      Should return:
   *          > -1 if the item should be located at a lower index than the provided item.
   *          > 1 if the item should be located at a higher index than the provided item.
   *          > 0 if the item is the item you're looking for.
   *
   * @returns the object if found, otherwise returns null
   */
  search: function(r, e) {
    let t = 0, i = r.length - 1, s = null, n = null;
    for (; t <= i; ) {
      s = (t + i) / 2 | 0, n = r[s];
      const a = e(n);
      if (a > 0)
        t = s + 1;
      else if (a < 0)
        i = s - 1;
      else
        return n;
    }
    return null;
  }
};
function vC(r, e, t) {
  if (e === null || !Array.isArray(r) || !r.length || !q(e))
    return null;
  const i = r[0].programDateTime;
  if (e < (i || 0))
    return null;
  const s = r[r.length - 1].endProgramDateTime;
  if (e >= (s || 0))
    return null;
  for (let n = 0; n < r.length; ++n) {
    const a = r[n];
    if (SC(e, t, a))
      return a;
  }
  return null;
}
function Hs(r, e, t = 0, i = 0, s = 5e-3) {
  let n = null;
  if (r) {
    n = e[1 + r.sn - e[0].sn] || null;
    const o = r.endDTS - t;
    o > 0 && o < 15e-7 && (t += 15e-7), n && r.level !== n.level && n.end <= r.end && (n = e[2 + r.sn - e[0].sn] || null);
  } else t === 0 && e[0].start === 0 && (n = e[0]);
  if (n && ((!r || r.level === n.level) && np(t, i, n) === 0 || EC(n, r, Math.min(s, i))))
    return n;
  const a = i_.search(e, np.bind(null, t, i));
  return a && (a !== r || !n) ? a : n;
}
function EC(r, e, t) {
  if (e && e.start === 0 && e.level < r.level && (e.endPTS || 0) > 0) {
    const i = e.tagList.reduce((s, n) => (n[0] === "INF" && (s += parseFloat(n[1])), s), t);
    return r.start <= i;
  }
  return !1;
}
function np(r = 0, e = 0, t) {
  if (t.start <= r && t.start + t.duration > r)
    return 0;
  const i = Math.min(e, t.duration + (t.deltaPTS ? t.deltaPTS : 0));
  return t.start + t.duration - i <= r ? 1 : t.start - i > r && t.start ? -1 : 0;
}
function SC(r, e, t) {
  const i = Math.min(e, t.duration + (t.deltaPTS ? t.deltaPTS : 0)) * 1e3;
  return (t.endProgramDateTime || 0) - i > r;
}
function s_(r, e, t) {
  if (r && r.startCC <= e && r.endCC >= e) {
    let i = r.fragments;
    const {
      fragmentHint: s
    } = r;
    s && (i = i.concat(s));
    let n;
    return i_.search(i, (a) => a.cc < e ? 1 : a.cc > e ? -1 : (n = a, a.end <= t ? 1 : a.start > t ? -1 : 0)), n || null;
  }
  return null;
}
function ro(r) {
  switch (r.details) {
    case V.FRAG_LOAD_TIMEOUT:
    case V.KEY_LOAD_TIMEOUT:
    case V.LEVEL_LOAD_TIMEOUT:
    case V.MANIFEST_LOAD_TIMEOUT:
      return !0;
  }
  return !1;
}
function ap(r, e) {
  const t = ro(e);
  return r.default[`${t ? "timeout" : "error"}Retry`];
}
function Hd(r, e) {
  const t = r.backoff === "linear" ? 1 : Math.pow(2, e);
  return Math.min(t * r.retryDelayMs, r.maxRetryDelayMs);
}
function op(r) {
  return we(we({}, r), {
    errorRetry: null,
    timeoutRetry: null
  });
}
function no(r, e, t, i) {
  if (!r)
    return !1;
  const s = i == null ? void 0 : i.code, n = e < r.maxNumRetry && (TC(s) || !!t);
  return r.shouldRetry ? r.shouldRetry(r, e, t, i, n) : n;
}
function TC(r) {
  return kc(r) || !!r && (r < 400 || r > 499);
}
function kc(r) {
  return r === 0 && navigator.onLine === !1;
}
var ft = {
  DoNothing: 0,
  SendAlternateToPenaltyBox: 2,
  RemoveAlternatePermanently: 3,
  RetryRequest: 5
}, Vt = {
  None: 0,
  MoveAllAlternatesMatchingHost: 1,
  MoveAllAlternatesMatchingHDCP: 2,
  MoveAllAlternatesMatchingKey: 4
};
class bC extends qt {
  constructor(e) {
    super("error-controller", e.logger), this.hls = void 0, this.playlistError = 0, this.hls = e, this.registerListeners();
  }
  registerListeners() {
    const e = this.hls;
    e.on(T.ERROR, this.onError, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.LEVEL_UPDATED, this.onLevelUpdated, this);
  }
  unregisterListeners() {
    const e = this.hls;
    e && (e.off(T.ERROR, this.onError, this), e.off(T.ERROR, this.onErrorOut, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.LEVEL_UPDATED, this.onLevelUpdated, this));
  }
  destroy() {
    this.unregisterListeners(), this.hls = null;
  }
  startLoad(e) {
  }
  stopLoad() {
    this.playlistError = 0;
  }
  getVariantLevelIndex(e) {
    return (e == null ? void 0 : e.type) === te.MAIN ? e.level : this.getVariantIndex();
  }
  getVariantIndex() {
    var e;
    const t = this.hls, i = t.currentLevel;
    return (e = t.loadLevelObj) != null && e.details || i === -1 ? t.loadLevel : i;
  }
  variantHasKey(e, t) {
    if (e) {
      var i;
      if ((i = e.details) != null && i.hasKey(t))
        return !0;
      const s = e.audioGroups;
      if (s)
        return this.hls.allAudioTracks.filter((a) => s.indexOf(a.groupId) >= 0).some((a) => {
          var o;
          return (o = a.details) == null ? void 0 : o.hasKey(t);
        });
    }
    return !1;
  }
  onManifestLoading() {
    this.playlistError = 0;
  }
  onLevelUpdated() {
    this.playlistError = 0;
  }
  onError(e, t) {
    var i;
    if (t.fatal)
      return;
    const s = this.hls, n = t.context;
    switch (t.details) {
      case V.FRAG_LOAD_ERROR:
      case V.FRAG_LOAD_TIMEOUT:
      case V.KEY_LOAD_ERROR:
      case V.KEY_LOAD_TIMEOUT:
        t.errorAction = this.getFragRetryOrSwitchAction(t);
        return;
      case V.FRAG_PARSING_ERROR:
        if ((i = t.frag) != null && i.gap) {
          t.errorAction = Tr();
          return;
        }
      case V.FRAG_GAP:
      case V.FRAG_DECRYPT_ERROR: {
        t.errorAction = this.getFragRetryOrSwitchAction(t), t.errorAction.action = ft.SendAlternateToPenaltyBox;
        return;
      }
      case V.LEVEL_EMPTY_ERROR:
      case V.LEVEL_PARSING_ERROR:
        {
          var a;
          const c = t.parent === te.MAIN ? t.level : s.loadLevel;
          t.details === V.LEVEL_EMPTY_ERROR && ((a = t.context) != null && (a = a.levelDetails) != null && a.live) ? t.errorAction = this.getPlaylistRetryOrSwitchAction(t, c) : (t.levelRetry = !1, t.errorAction = this.getLevelSwitchAction(t, c));
        }
        return;
      case V.LEVEL_LOAD_ERROR:
      case V.LEVEL_LOAD_TIMEOUT:
        typeof (n == null ? void 0 : n.level) == "number" && (t.errorAction = this.getPlaylistRetryOrSwitchAction(t, n.level));
        return;
      case V.AUDIO_TRACK_LOAD_ERROR:
      case V.AUDIO_TRACK_LOAD_TIMEOUT:
      case V.SUBTITLE_LOAD_ERROR:
      case V.SUBTITLE_TRACK_LOAD_TIMEOUT:
        if (n) {
          const c = s.loadLevelObj;
          if (c && (n.type === me.AUDIO_TRACK && c.hasAudioGroup(n.groupId) || n.type === me.SUBTITLE_TRACK && c.hasSubtitleGroup(n.groupId))) {
            t.errorAction = this.getPlaylistRetryOrSwitchAction(t, s.loadLevel), t.errorAction.action = ft.SendAlternateToPenaltyBox, t.errorAction.flags = Vt.MoveAllAlternatesMatchingHost;
            return;
          }
        }
        return;
      case V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
        t.errorAction = {
          action: ft.SendAlternateToPenaltyBox,
          flags: Vt.MoveAllAlternatesMatchingHDCP
        };
        return;
      case V.KEY_SYSTEM_SESSION_UPDATE_FAILED:
      case V.KEY_SYSTEM_STATUS_INTERNAL_ERROR:
      case V.KEY_SYSTEM_NO_SESSION:
        t.errorAction = {
          action: ft.SendAlternateToPenaltyBox,
          flags: Vt.MoveAllAlternatesMatchingKey
        };
        return;
      case V.BUFFER_ADD_CODEC_ERROR:
      case V.REMUX_ALLOC_ERROR:
      case V.BUFFER_APPEND_ERROR:
        if (!t.errorAction) {
          var o;
          t.errorAction = this.getLevelSwitchAction(t, (o = t.level) != null ? o : s.loadLevel);
        }
        return;
      case V.INTERNAL_EXCEPTION:
      case V.BUFFER_APPENDING_ERROR:
      case V.BUFFER_FULL_ERROR:
      case V.LEVEL_SWITCH_ERROR:
      case V.BUFFER_STALLED_ERROR:
      case V.BUFFER_SEEK_OVER_HOLE:
      case V.BUFFER_NUDGE_ON_STALL:
        t.errorAction = Tr();
        return;
    }
    t.type === ie.KEY_SYSTEM_ERROR && (t.levelRetry = !1, t.errorAction = Tr());
  }
  getPlaylistRetryOrSwitchAction(e, t) {
    const i = this.hls, s = ap(i.config.playlistLoadPolicy, e), n = this.playlistError++;
    if (no(s, n, ro(e), e.response))
      return {
        action: ft.RetryRequest,
        flags: Vt.None,
        retryConfig: s,
        retryCount: n
      };
    const o = this.getLevelSwitchAction(e, t);
    return s && (o.retryConfig = s, o.retryCount = n), o;
  }
  getFragRetryOrSwitchAction(e) {
    const t = this.hls, i = this.getVariantLevelIndex(e.frag), s = t.levels[i], {
      fragLoadPolicy: n,
      keyLoadPolicy: a
    } = t.config, o = ap(e.details.startsWith("key") ? a : n, e), c = t.levels.reduce((d, h) => d + h.fragmentError, 0);
    if (s && (e.details !== V.FRAG_GAP && s.fragmentError++, no(o, c, ro(e), e.response)))
      return {
        action: ft.RetryRequest,
        flags: Vt.None,
        retryConfig: o,
        retryCount: c
      };
    const l = this.getLevelSwitchAction(e, i);
    return o && (l.retryConfig = o, l.retryCount = c), l;
  }
  getLevelSwitchAction(e, t) {
    const i = this.hls;
    t == null && (t = i.loadLevel);
    const s = this.hls.levels[t];
    if (s) {
      var n, a;
      const l = e.details;
      s.loadError++, l === V.BUFFER_APPEND_ERROR && s.fragmentError++;
      let d = -1;
      const {
        levels: h,
        loadLevel: u,
        minAutoLevel: f,
        maxAutoLevel: p
      } = i;
      !i.autoLevelEnabled && !i.config.preserveManualLevelOnError && (i.loadLevel = -1);
      const m = (n = e.frag) == null ? void 0 : n.type, x = (m === te.AUDIO && l === V.FRAG_PARSING_ERROR || e.sourceBufferName === "audio" && (l === V.BUFFER_ADD_CODEC_ERROR || l === V.BUFFER_APPEND_ERROR)) && h.some(({
        audioCodec: A
      }) => s.audioCodec !== A), v = e.sourceBufferName === "video" && (l === V.BUFFER_ADD_CODEC_ERROR || l === V.BUFFER_APPEND_ERROR) && h.some(({
        codecSet: A,
        audioCodec: C
      }) => s.codecSet !== A && s.audioCodec === C), {
        type: E,
        groupId: b
      } = (a = e.context) != null ? a : {};
      for (let A = h.length; A--; ) {
        const C = (A + u) % h.length;
        if (C !== u && C >= f && C <= p && h[C].loadError === 0) {
          var o, c;
          const I = h[C];
          if (l === V.FRAG_GAP && m === te.MAIN && e.frag) {
            const L = h[C].details;
            if (L) {
              const R = Hs(e.frag, L.fragments, e.frag.start);
              if (R != null && R.gap)
                continue;
            }
          } else {
            if (E === me.AUDIO_TRACK && I.hasAudioGroup(b) || E === me.SUBTITLE_TRACK && I.hasSubtitleGroup(b))
              continue;
            if (m === te.AUDIO && (o = s.audioGroups) != null && o.some((L) => I.hasAudioGroup(L)) || m === te.SUBTITLE && (c = s.subtitleGroups) != null && c.some((L) => I.hasSubtitleGroup(L)) || x && s.audioCodec === I.audioCodec || v && s.codecSet === I.codecSet || !x && s.codecSet !== I.codecSet)
              continue;
          }
          d = C;
          break;
        }
      }
      if (d > -1 && i.loadLevel !== d)
        return e.levelRetry = !0, this.playlistError = 0, {
          action: ft.SendAlternateToPenaltyBox,
          flags: Vt.None,
          nextAutoLevel: d
        };
    }
    return {
      action: ft.SendAlternateToPenaltyBox,
      flags: Vt.MoveAllAlternatesMatchingHost
    };
  }
  onErrorOut(e, t) {
    var i;
    switch ((i = t.errorAction) == null ? void 0 : i.action) {
      case ft.DoNothing:
        break;
      case ft.SendAlternateToPenaltyBox:
        this.sendAlternateToPenaltyBox(t), !t.errorAction.resolved && t.details !== V.FRAG_GAP ? t.fatal = !0 : /MediaSource readyState: ended/.test(t.error.message) && (this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`), this.hls.recoverMediaError());
        break;
    }
    if (t.fatal) {
      this.hls.stopLoad();
      return;
    }
  }
  sendAlternateToPenaltyBox(e) {
    const t = this.hls, i = e.errorAction;
    if (!i)
      return;
    const {
      flags: s
    } = i, n = i.nextAutoLevel;
    switch (s) {
      case Vt.None:
        this.switchLevel(e, n);
        break;
      case Vt.MoveAllAlternatesMatchingHDCP: {
        const c = this.getVariantLevelIndex(e.frag), l = t.levels[c], d = l == null ? void 0 : l.attrs["HDCP-LEVEL"];
        if (i.hdcpLevel = d, d) {
          t.maxHdcpLevel = Pc[Pc.indexOf(d) - 1], i.resolved = !0, this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);
          break;
        }
      }
      case Vt.MoveAllAlternatesMatchingKey: {
        const c = e.decryptdata;
        if (c) {
          const l = this.hls.levels;
          for (let d = l.length; d--; )
            if (this.variantHasKey(l[d], c)) {
              var a, o;
              this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(a = l[d].audioGroups) == null ? void 0 : a.join(",")}" (${(o = e.frag) == null ? void 0 : o.type} fragment) ${Wt(c.keyId || [])}`), l[d].fragmentError++, l[d].loadError++, this.log(`Removing level ${d} with key error (${e.error})`), this.hls.removeLevel(d);
            }
          l.length && (i.resolved = !0);
        }
        break;
      }
    }
    i.resolved || this.switchLevel(e, n);
  }
  switchLevel(e, t) {
    if (t !== void 0 && e.errorAction && (this.warn(`switching to level ${t} after ${e.details}`), this.hls.nextAutoLevel = t, e.errorAction.resolved = !0, this.hls.nextLoadLevel = this.hls.nextAutoLevel, e.details === V.BUFFER_ADD_CODEC_ERROR && e.mimeType && e.sourceBufferName !== "audiovideo")) {
      const i = Dc(e.mimeType), s = this.hls.levels;
      for (let n = s.length; n--; )
        s[n][`${e.sourceBufferName}Codec`] === i && (this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`), this.hls.removeLevel(n));
    }
  }
}
function Tr(r) {
  const e = {
    action: ft.DoNothing,
    flags: Vt.None
  };
  return r && (e.resolved = !0), e;
}
var nt = {
  NOT_LOADED: "NOT_LOADED",
  APPENDING: "APPENDING",
  PARTIAL: "PARTIAL",
  OK: "OK"
};
class AC {
  constructor(e) {
    this.activePartLists = /* @__PURE__ */ Object.create(null), this.endListFragments = /* @__PURE__ */ Object.create(null), this.fragments = /* @__PURE__ */ Object.create(null), this.timeRanges = /* @__PURE__ */ Object.create(null), this.bufferPadding = 0.2, this.hls = void 0, this.hasGaps = !1, this.hls = e, this._registerListeners();
  }
  _registerListeners() {
    const {
      hls: e
    } = this;
    e && (e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.BUFFER_APPENDED, this.onBufferAppended, this), e.on(T.FRAG_BUFFERED, this.onFragBuffered, this), e.on(T.FRAG_LOADED, this.onFragLoaded, this));
  }
  _unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.BUFFER_APPENDED, this.onBufferAppended, this), e.off(T.FRAG_BUFFERED, this.onFragBuffered, this), e.off(T.FRAG_LOADED, this.onFragLoaded, this));
  }
  destroy() {
    this._unregisterListeners(), this.hls = // @ts-ignore
    this.fragments = // @ts-ignore
    this.activePartLists = // @ts-ignore
    this.endListFragments = this.timeRanges = null;
  }
  /**
   * Return a Fragment or Part with an appended range that matches the position and levelType
   * Otherwise, return null
   */
  getAppendedFrag(e, t) {
    const i = this.activePartLists[t];
    if (i)
      for (let s = i.length; s--; ) {
        const n = i[s];
        if (!n)
          break;
        if (n.start <= e && e <= n.end && n.loaded)
          return n;
      }
    return this.getBufferedFrag(e, t);
  }
  /**
   * Return a buffered Fragment that matches the position and levelType.
   * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
   * If not found any Fragment, return null
   */
  getBufferedFrag(e, t) {
    return this.getFragAtPos(e, t, !0);
  }
  getFragAtPos(e, t, i) {
    const {
      fragments: s
    } = this, n = Object.keys(s);
    for (let a = n.length; a--; ) {
      const o = s[n[a]];
      if ((o == null ? void 0 : o.body.type) === t && (!i || o.buffered)) {
        const c = o.body;
        if (c.start <= e && e <= c.end)
          return c;
      }
    }
    return null;
  }
  /**
   * Partial fragments effected by coded frame eviction will be removed
   * The browser will unload parts of the buffer to free up memory for new buffer data
   * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
   */
  detectEvictedFragments(e, t, i, s, n) {
    this.timeRanges && (this.timeRanges[e] = t);
    const a = (s == null ? void 0 : s.fragment.sn) || -1;
    Object.keys(this.fragments).forEach((o) => {
      const c = this.fragments[o];
      if (!c || a >= c.body.sn)
        return;
      if (!c.buffered && (!c.loaded || n)) {
        c.body.type === i && this.removeFragment(c.body);
        return;
      }
      const l = c.range[e];
      if (l) {
        if (l.time.length === 0) {
          this.removeFragment(c.body);
          return;
        }
        l.time.some((d) => {
          const h = !this.isTimeBuffered(d.startPTS, d.endPTS, t);
          return h && this.removeFragment(c.body), h;
        });
      }
    });
  }
  /**
   * Checks if the fragment passed in is loaded in the buffer properly
   * Partially loaded fragments will be registered as a partial fragment
   */
  detectPartialFragments(e) {
    const t = this.timeRanges;
    if (!t || e.frag.sn === "initSegment")
      return;
    const i = e.frag, s = ir(i), n = this.fragments[s];
    if (!n || n.buffered && i.gap)
      return;
    const a = !i.relurl;
    Object.keys(t).forEach((o) => {
      const c = i.elementaryStreams[o];
      if (!c)
        return;
      const l = t[o], d = a || c.partial === !0;
      n.range[o] = this.getBufferedTimes(i, e.part, d, l);
    }), n.loaded = null, Object.keys(n.range).length ? (n.buffered = !0, (n.body.endList = i.endList || n.body.endList) && (this.endListFragments[n.body.type] = n), Qn(n) || this.removeParts(i.sn - 1, i.type)) : this.removeFragment(n.body);
  }
  removeParts(e, t) {
    const i = this.activePartLists[t];
    i && (this.activePartLists[t] = lp(i, (s) => s.fragment.sn >= e));
  }
  fragBuffered(e, t) {
    const i = ir(e);
    let s = this.fragments[i];
    !s && t && (s = this.fragments[i] = {
      body: e,
      appendedPTS: null,
      loaded: null,
      buffered: !1,
      range: /* @__PURE__ */ Object.create(null)
    }, e.gap && (this.hasGaps = !0)), s && (s.loaded = null, s.buffered = !0);
  }
  getBufferedTimes(e, t, i, s) {
    const n = {
      time: [],
      partial: i
    }, a = e.start, o = e.end, c = e.minEndPTS || o, l = e.maxStartPTS || a;
    for (let d = 0; d < s.length; d++) {
      const h = s.start(d) - this.bufferPadding, u = s.end(d) + this.bufferPadding;
      if (l >= h && c <= u) {
        n.time.push({
          startPTS: Math.max(a, s.start(d)),
          endPTS: Math.min(o, s.end(d))
        });
        break;
      } else if (a < u && o > h) {
        const f = Math.max(a, s.start(d)), p = Math.min(o, s.end(d));
        p > f && (n.partial = !0, n.time.push({
          startPTS: f,
          endPTS: p
        }));
      } else if (o <= h)
        break;
    }
    return n;
  }
  /**
   * Gets the partial fragment for a certain time
   */
  getPartialFragment(e) {
    let t = null, i, s, n, a = 0;
    const {
      bufferPadding: o,
      fragments: c
    } = this;
    return Object.keys(c).forEach((l) => {
      const d = c[l];
      d && Qn(d) && (s = d.body.start - o, n = d.body.end + o, e >= s && e <= n && (i = Math.min(e - s, n - e), a <= i && (t = d.body, a = i)));
    }), t;
  }
  isEndListAppended(e) {
    const t = this.endListFragments[e];
    return t !== void 0 && (t.buffered || Qn(t));
  }
  getState(e) {
    const t = ir(e), i = this.fragments[t];
    return i ? i.buffered ? Qn(i) ? nt.PARTIAL : nt.OK : nt.APPENDING : nt.NOT_LOADED;
  }
  isTimeBuffered(e, t, i) {
    let s, n;
    for (let a = 0; a < i.length; a++) {
      if (s = i.start(a) - this.bufferPadding, n = i.end(a) + this.bufferPadding, e >= s && t <= n)
        return !0;
      if (t <= s)
        return !1;
    }
    return !1;
  }
  onManifestLoading() {
    this.removeAllFragments();
  }
  onFragLoaded(e, t) {
    if (t.frag.sn === "initSegment" || t.frag.bitrateTest)
      return;
    const i = t.frag, s = t.part ? null : t, n = ir(i);
    this.fragments[n] = {
      body: i,
      appendedPTS: null,
      loaded: s,
      buffered: !1,
      range: /* @__PURE__ */ Object.create(null)
    };
  }
  onBufferAppended(e, t) {
    const {
      frag: i,
      part: s,
      timeRanges: n,
      type: a
    } = t;
    if (i.sn === "initSegment")
      return;
    const o = i.type;
    if (s) {
      let l = this.activePartLists[o];
      l || (this.activePartLists[o] = l = []), l.push(s);
    }
    this.timeRanges = n;
    const c = n[a];
    this.detectEvictedFragments(a, c, o, s);
  }
  onFragBuffered(e, t) {
    this.detectPartialFragments(t);
  }
  hasFragment(e) {
    const t = ir(e);
    return !!this.fragments[t];
  }
  hasFragments(e) {
    const {
      fragments: t
    } = this, i = Object.keys(t);
    if (!e)
      return i.length > 0;
    for (let s = i.length; s--; ) {
      const n = t[i[s]];
      if ((n == null ? void 0 : n.body.type) === e)
        return !0;
    }
    return !1;
  }
  hasParts(e) {
    var t;
    return !!((t = this.activePartLists[e]) != null && t.length);
  }
  removeFragmentsInRange(e, t, i, s, n) {
    s && !this.hasGaps || Object.keys(this.fragments).forEach((a) => {
      const o = this.fragments[a];
      if (!o)
        return;
      const c = o.body;
      c.type !== i || s && !c.gap || c.start < t && c.end > e && (o.buffered || n) && this.removeFragment(c);
    });
  }
  removeFragment(e) {
    const t = ir(e);
    e.clearElementaryStreamInfo();
    const i = this.activePartLists[e.type];
    if (i) {
      const s = e.sn;
      this.activePartLists[e.type] = lp(i, (n) => n.fragment.sn !== s);
    }
    delete this.fragments[t], e.endList && delete this.endListFragments[e.type];
  }
  removeAllFragments() {
    var e;
    this.fragments = /* @__PURE__ */ Object.create(null), this.endListFragments = /* @__PURE__ */ Object.create(null), this.activePartLists = /* @__PURE__ */ Object.create(null), this.hasGaps = !1;
    const t = (e = this.hls) == null || (e = e.latestLevelDetails) == null ? void 0 : e.partList;
    t && t.forEach((i) => i.clearElementaryStreamInfo());
  }
}
function Qn(r) {
  var e, t, i;
  return r.buffered && !!(r.body.gap || (e = r.range.video) != null && e.partial || (t = r.range.audio) != null && t.partial || (i = r.range.audiovideo) != null && i.partial);
}
function ir(r) {
  return `${r.type}_${r.level}_${r.sn}`;
}
function lp(r, e) {
  return r.filter((t) => {
    const i = e(t);
    return i || t.clearElementaryStreamInfo(), i;
  });
}
var xs = {
  cbc: 0,
  ctr: 1
};
class CC {
  constructor(e, t, i) {
    this.subtle = void 0, this.aesIV = void 0, this.aesMode = void 0, this.subtle = e, this.aesIV = t, this.aesMode = i;
  }
  decrypt(e, t) {
    switch (this.aesMode) {
      case xs.cbc:
        return this.subtle.decrypt({
          name: "AES-CBC",
          iv: this.aesIV
        }, t, e);
      case xs.ctr:
        return this.subtle.decrypt(
          {
            name: "AES-CTR",
            counter: this.aesIV,
            length: 64
          },
          //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
          t,
          e
        );
      default:
        throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
    }
  }
}
function RC(r) {
  const e = r.byteLength, t = e && new DataView(r.buffer).getUint8(e - 1);
  return t ? r.slice(0, e - t) : r;
}
class IC {
  constructor() {
    this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], this.sBox = new Uint32Array(256), this.invSBox = new Uint32Array(256), this.key = new Uint32Array(0), this.ksRows = 0, this.keySize = 0, this.keySchedule = void 0, this.invKeySchedule = void 0, this.initTable();
  }
  // Using view.getUint32() also swaps the byte order.
  uint8ArrayToUint32Array_(e) {
    const t = new DataView(e), i = new Uint32Array(4);
    for (let s = 0; s < 4; s++)
      i[s] = t.getUint32(s * 4);
    return i;
  }
  initTable() {
    const e = this.sBox, t = this.invSBox, i = this.subMix, s = i[0], n = i[1], a = i[2], o = i[3], c = this.invSubMix, l = c[0], d = c[1], h = c[2], u = c[3], f = new Uint32Array(256);
    let p = 0, m = 0, g = 0;
    for (g = 0; g < 256; g++)
      g < 128 ? f[g] = g << 1 : f[g] = g << 1 ^ 283;
    for (g = 0; g < 256; g++) {
      let x = m ^ m << 1 ^ m << 2 ^ m << 3 ^ m << 4;
      x = x >>> 8 ^ x & 255 ^ 99, e[p] = x, t[x] = p;
      const _ = f[p], v = f[_], E = f[v];
      let b = f[x] * 257 ^ x * 16843008;
      s[p] = b << 24 | b >>> 8, n[p] = b << 16 | b >>> 16, a[p] = b << 8 | b >>> 24, o[p] = b, b = E * 16843009 ^ v * 65537 ^ _ * 257 ^ p * 16843008, l[x] = b << 24 | b >>> 8, d[x] = b << 16 | b >>> 16, h[x] = b << 8 | b >>> 24, u[x] = b, p ? (p = _ ^ f[f[f[E ^ _]]], m ^= f[f[m]]) : p = m = 1;
    }
  }
  expandKey(e) {
    const t = this.uint8ArrayToUint32Array_(e);
    let i = !0, s = 0;
    for (; s < t.length && i; )
      i = t[s] === this.key[s], s++;
    if (i)
      return;
    this.key = t;
    const n = this.keySize = t.length;
    if (n !== 4 && n !== 6 && n !== 8)
      throw new Error("Invalid aes key size=" + n);
    const a = this.ksRows = (n + 6 + 1) * 4;
    let o, c;
    const l = this.keySchedule = new Uint32Array(a), d = this.invKeySchedule = new Uint32Array(a), h = this.sBox, u = this.rcon, f = this.invSubMix, p = f[0], m = f[1], g = f[2], x = f[3];
    let _, v;
    for (o = 0; o < a; o++) {
      if (o < n) {
        _ = l[o] = t[o];
        continue;
      }
      v = _, o % n === 0 ? (v = v << 8 | v >>> 24, v = h[v >>> 24] << 24 | h[v >>> 16 & 255] << 16 | h[v >>> 8 & 255] << 8 | h[v & 255], v ^= u[o / n | 0] << 24) : n > 6 && o % n === 4 && (v = h[v >>> 24] << 24 | h[v >>> 16 & 255] << 16 | h[v >>> 8 & 255] << 8 | h[v & 255]), l[o] = _ = (l[o - n] ^ v) >>> 0;
    }
    for (c = 0; c < a; c++)
      o = a - c, c & 3 ? v = l[o] : v = l[o - 4], c < 4 || o <= 4 ? d[c] = v : d[c] = p[h[v >>> 24]] ^ m[h[v >>> 16 & 255]] ^ g[h[v >>> 8 & 255]] ^ x[h[v & 255]], d[c] = d[c] >>> 0;
  }
  // Adding this as a method greatly improves performance.
  networkToHostOrderSwap(e) {
    return e << 24 | (e & 65280) << 8 | (e & 16711680) >> 8 | e >>> 24;
  }
  decrypt(e, t, i) {
    const s = this.keySize + 6, n = this.invKeySchedule, a = this.invSBox, o = this.invSubMix, c = o[0], l = o[1], d = o[2], h = o[3], u = this.uint8ArrayToUint32Array_(i);
    let f = u[0], p = u[1], m = u[2], g = u[3];
    const x = new Int32Array(e), _ = new Int32Array(x.length);
    let v, E, b, A, C, I, L, R, D, M, w, N, H, G;
    const Z = this.networkToHostOrderSwap;
    for (; t < x.length; ) {
      for (D = Z(x[t]), M = Z(x[t + 1]), w = Z(x[t + 2]), N = Z(x[t + 3]), C = D ^ n[0], I = N ^ n[1], L = w ^ n[2], R = M ^ n[3], H = 4, G = 1; G < s; G++)
        v = c[C >>> 24] ^ l[I >> 16 & 255] ^ d[L >> 8 & 255] ^ h[R & 255] ^ n[H], E = c[I >>> 24] ^ l[L >> 16 & 255] ^ d[R >> 8 & 255] ^ h[C & 255] ^ n[H + 1], b = c[L >>> 24] ^ l[R >> 16 & 255] ^ d[C >> 8 & 255] ^ h[I & 255] ^ n[H + 2], A = c[R >>> 24] ^ l[C >> 16 & 255] ^ d[I >> 8 & 255] ^ h[L & 255] ^ n[H + 3], C = v, I = E, L = b, R = A, H = H + 4;
      v = a[C >>> 24] << 24 ^ a[I >> 16 & 255] << 16 ^ a[L >> 8 & 255] << 8 ^ a[R & 255] ^ n[H], E = a[I >>> 24] << 24 ^ a[L >> 16 & 255] << 16 ^ a[R >> 8 & 255] << 8 ^ a[C & 255] ^ n[H + 1], b = a[L >>> 24] << 24 ^ a[R >> 16 & 255] << 16 ^ a[C >> 8 & 255] << 8 ^ a[I & 255] ^ n[H + 2], A = a[R >>> 24] << 24 ^ a[C >> 16 & 255] << 16 ^ a[I >> 8 & 255] << 8 ^ a[L & 255] ^ n[H + 3], _[t] = Z(v ^ f), _[t + 1] = Z(A ^ p), _[t + 2] = Z(b ^ m), _[t + 3] = Z(E ^ g), f = D, p = M, m = w, g = N, t = t + 4;
    }
    return _.buffer;
  }
}
class LC {
  constructor(e, t, i) {
    this.subtle = void 0, this.key = void 0, this.aesMode = void 0, this.subtle = e, this.key = t, this.aesMode = i;
  }
  expandKey() {
    const e = DC(this.aesMode);
    return this.subtle.importKey("raw", this.key, {
      name: e
    }, !1, ["encrypt", "decrypt"]);
  }
}
function DC(r) {
  switch (r) {
    case xs.cbc:
      return "AES-CBC";
    case xs.ctr:
      return "AES-CTR";
    default:
      throw new Error(`[FastAESKey] invalid aes mode ${r}`);
  }
}
const PC = 16;
class Zd {
  constructor(e, {
    removePKCS7Padding: t = !0
  } = {}) {
    if (this.logEnabled = !0, this.removePKCS7Padding = void 0, this.subtle = null, this.softwareDecrypter = null, this.key = null, this.fastAesKey = null, this.remainderData = null, this.currentIV = null, this.currentResult = null, this.useSoftware = void 0, this.enableSoftwareAES = void 0, this.enableSoftwareAES = e.enableSoftwareAES, this.removePKCS7Padding = t, t)
      try {
        const i = self.crypto;
        i && (this.subtle = i.subtle || i.webkitSubtle);
      } catch {
      }
    this.useSoftware = !this.subtle;
  }
  destroy() {
    this.subtle = null, this.softwareDecrypter = null, this.key = null, this.fastAesKey = null, this.remainderData = null, this.currentIV = null, this.currentResult = null;
  }
  isSync() {
    return this.useSoftware;
  }
  flush() {
    const {
      currentResult: e,
      remainderData: t
    } = this;
    if (!e || t)
      return this.reset(), null;
    const i = new Uint8Array(e);
    return this.reset(), this.removePKCS7Padding ? RC(i) : i;
  }
  reset() {
    this.currentResult = null, this.currentIV = null, this.remainderData = null, this.softwareDecrypter && (this.softwareDecrypter = null);
  }
  decrypt(e, t, i, s) {
    return this.useSoftware ? new Promise((n, a) => {
      const o = ArrayBuffer.isView(e) ? e : new Uint8Array(e);
      this.softwareDecrypt(o, t, i, s);
      const c = this.flush();
      c ? n(c.buffer) : a(new Error("[softwareDecrypt] Failed to decrypt data"));
    }) : this.webCryptoDecrypt(new Uint8Array(e), t, i, s);
  }
  // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  // data is handled in the flush() call
  softwareDecrypt(e, t, i, s) {
    const {
      currentIV: n,
      currentResult: a,
      remainderData: o
    } = this;
    if (s !== xs.cbc || t.byteLength !== 16)
      return Pe.warn("SoftwareDecrypt: can only handle AES-128-CBC"), null;
    this.logOnce("JS AES decrypt"), o && (e = Qt(o, e), this.remainderData = null);
    const c = this.getValidChunk(e);
    if (!c.length)
      return null;
    n && (i = n);
    let l = this.softwareDecrypter;
    l || (l = this.softwareDecrypter = new IC()), l.expandKey(t);
    const d = a;
    return this.currentResult = l.decrypt(c.buffer, 0, i), this.currentIV = c.slice(-16).buffer, d || null;
  }
  webCryptoDecrypt(e, t, i, s) {
    if (this.key !== t || !this.fastAesKey) {
      if (!this.subtle)
        return Promise.resolve(this.onWebCryptoError(e, t, i, s));
      this.key = t, this.fastAesKey = new LC(this.subtle, t, s);
    }
    return this.fastAesKey.expandKey().then((n) => this.subtle ? (this.logOnce("WebCrypto AES decrypt"), new CC(this.subtle, new Uint8Array(i), s).decrypt(e.buffer, n)) : Promise.reject(new Error("web crypto not initialized"))).catch((n) => (Pe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`), this.onWebCryptoError(e, t, i, s)));
  }
  onWebCryptoError(e, t, i, s) {
    const n = this.enableSoftwareAES;
    if (n) {
      this.useSoftware = !0, this.logEnabled = !0, this.softwareDecrypt(e, t, i, s);
      const a = this.flush();
      if (a)
        return a.buffer;
    }
    throw new Error("WebCrypto" + (n ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  }
  getValidChunk(e) {
    let t = e;
    const i = e.length - e.length % PC;
    return i !== e.length && (t = e.slice(0, i), this.remainderData = e.slice(i)), t;
  }
  logOnce(e) {
    this.logEnabled && (Pe.log(`[decrypter]: ${e}`), this.logEnabled = !1);
  }
}
const cp = Math.pow(2, 17);
class kC {
  constructor(e) {
    this.config = void 0, this.loader = null, this.partLoadTimeout = -1, this.config = e;
  }
  destroy() {
    this.loader && (this.loader.destroy(), this.loader = null);
  }
  abort() {
    this.loader && this.loader.abort();
  }
  load(e, t) {
    const i = e.url;
    if (!i)
      return Promise.reject(new Zi({
        type: ie.NETWORK_ERROR,
        details: V.FRAG_LOAD_ERROR,
        fatal: !1,
        frag: e,
        error: new Error(`Fragment does not have a ${i ? "part list" : "url"}`),
        networkDetails: null
      }));
    this.abort();
    const s = this.config, n = s.fLoader, a = s.loader;
    return new Promise((o, c) => {
      if (this.loader && this.loader.destroy(), e.gap)
        if (e.tagList.some((p) => p[0] === "GAP")) {
          c(hp(e));
          return;
        } else
          e.gap = !1;
      const l = this.loader = n ? new n(s) : new a(s), d = dp(e);
      e.loader = l;
      const h = op(s.fragLoadPolicy.default), u = {
        loadPolicy: h,
        timeout: h.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: e.sn === "initSegment" ? 1 / 0 : cp
      };
      e.stats = l.stats;
      const f = {
        onSuccess: (p, m, g, x) => {
          this.resetLoader(e, l);
          let _ = p.data;
          g.resetIV && e.decryptdata && (e.decryptdata.iv = new Uint8Array(_.slice(0, 16)), _ = _.slice(16)), o({
            frag: e,
            part: null,
            payload: _,
            networkDetails: x
          });
        },
        onError: (p, m, g, x) => {
          this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.FRAG_LOAD_ERROR,
            fatal: !1,
            frag: e,
            response: we({
              url: i,
              data: void 0
            }, p),
            error: new Error(`HTTP Error ${p.code} ${p.text}`),
            networkDetails: g,
            stats: x
          }));
        },
        onAbort: (p, m, g) => {
          this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.INTERNAL_ABORTED,
            fatal: !1,
            frag: e,
            error: new Error("Aborted"),
            networkDetails: g,
            stats: p
          }));
        },
        onTimeout: (p, m, g) => {
          this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.FRAG_LOAD_TIMEOUT,
            fatal: !1,
            frag: e,
            error: new Error(`Timeout after ${u.timeout}ms`),
            networkDetails: g,
            stats: p
          }));
        }
      };
      t && (f.onProgress = (p, m, g, x) => t({
        frag: e,
        part: null,
        payload: g,
        networkDetails: x
      })), l.load(d, u, f);
    });
  }
  loadPart(e, t, i) {
    this.abort();
    const s = this.config, n = s.fLoader, a = s.loader;
    return new Promise((o, c) => {
      if (this.loader && this.loader.destroy(), e.gap || t.gap) {
        c(hp(e, t));
        return;
      }
      const l = this.loader = n ? new n(s) : new a(s), d = dp(e, t);
      e.loader = l;
      const h = op(s.fragLoadPolicy.default), u = {
        loadPolicy: h,
        timeout: h.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: cp
      };
      t.stats = l.stats, l.load(d, u, {
        onSuccess: (f, p, m, g) => {
          this.resetLoader(e, l), this.updateStatsFromPart(e, t);
          const x = {
            frag: e,
            part: t,
            payload: f.data,
            networkDetails: g
          };
          i(x), o(x);
        },
        onError: (f, p, m, g) => {
          this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.FRAG_LOAD_ERROR,
            fatal: !1,
            frag: e,
            part: t,
            response: we({
              url: d.url,
              data: void 0
            }, f),
            error: new Error(`HTTP Error ${f.code} ${f.text}`),
            networkDetails: m,
            stats: g
          }));
        },
        onAbort: (f, p, m) => {
          e.stats.aborted = t.stats.aborted, this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.INTERNAL_ABORTED,
            fatal: !1,
            frag: e,
            part: t,
            error: new Error("Aborted"),
            networkDetails: m,
            stats: f
          }));
        },
        onTimeout: (f, p, m) => {
          this.resetLoader(e, l), c(new Zi({
            type: ie.NETWORK_ERROR,
            details: V.FRAG_LOAD_TIMEOUT,
            fatal: !1,
            frag: e,
            part: t,
            error: new Error(`Timeout after ${u.timeout}ms`),
            networkDetails: m,
            stats: f
          }));
        }
      });
    });
  }
  updateStatsFromPart(e, t) {
    const i = e.stats, s = t.stats, n = s.total;
    if (i.loaded += s.loaded, n) {
      const c = Math.round(e.duration / t.duration), l = Math.min(Math.round(i.loaded / n), c), h = (c - l) * Math.round(i.loaded / l);
      i.total = i.loaded + h;
    } else
      i.total = Math.max(i.loaded, i.total);
    const a = i.loading, o = s.loading;
    a.start ? a.first += o.first - o.start : (a.start = o.start, a.first = o.first), a.end = o.end;
  }
  resetLoader(e, t) {
    e.loader = null, this.loader === t && (self.clearTimeout(this.partLoadTimeout), this.loader = null), t.destroy();
  }
}
function dp(r, e = null) {
  const t = e || r, i = {
    frag: r,
    part: e,
    responseType: "arraybuffer",
    url: t.url,
    headers: {},
    rangeStart: 0,
    rangeEnd: 0
  }, s = t.byteRangeStartOffset, n = t.byteRangeEndOffset;
  if (q(s) && q(n)) {
    var a;
    let o = s, c = n;
    if (r.sn === "initSegment" && wC((a = r.decryptdata) == null ? void 0 : a.method)) {
      const l = n - s;
      l % 16 && (c = n + (16 - l % 16)), s !== 0 && (i.resetIV = !0, o = s - 16);
    }
    i.rangeStart = o, i.rangeEnd = c;
  }
  return i;
}
function hp(r, e) {
  const t = new Error(`GAP ${r.gap ? "tag" : "attribute"} found`), i = {
    type: ie.MEDIA_ERROR,
    details: V.FRAG_GAP,
    fatal: !1,
    frag: r,
    error: t,
    networkDetails: null
  };
  return e && (i.part = e), (e || r).stats.aborted = !0, new Zi(i);
}
function wC(r) {
  return r === "AES-128" || r === "AES-256";
}
class Zi extends Error {
  constructor(e) {
    super(e.error.message), this.data = void 0, this.data = e;
  }
}
class r_ extends qt {
  constructor(e, t) {
    super(e, t), this._boundTick = void 0, this._tickTimer = null, this._tickInterval = null, this._tickCallCount = 0, this._boundTick = this.tick.bind(this);
  }
  destroy() {
    this.onHandlerDestroying(), this.onHandlerDestroyed();
  }
  onHandlerDestroying() {
    this.clearNextTick(), this.clearInterval();
  }
  onHandlerDestroyed() {
  }
  hasInterval() {
    return !!this._tickInterval;
  }
  hasNextTick() {
    return !!this._tickTimer;
  }
  /**
   * @param millis - Interval time (ms)
   * @eturns True when interval has been scheduled, false when already scheduled (no effect)
   */
  setInterval(e) {
    return this._tickInterval ? !1 : (this._tickCallCount = 0, this._tickInterval = self.setInterval(this._boundTick, e), !0);
  }
  /**
   * @returns True when interval was cleared, false when none was set (no effect)
   */
  clearInterval() {
    return this._tickInterval ? (self.clearInterval(this._tickInterval), this._tickInterval = null, !0) : !1;
  }
  /**
   * @returns True when timeout was cleared, false when none was set (no effect)
   */
  clearNextTick() {
    return this._tickTimer ? (self.clearTimeout(this._tickTimer), this._tickTimer = null, !0) : !1;
  }
  /**
   * Will call the subclass doTick implementation in this main loop tick
   * or in the next one (via setTimeout(,0)) in case it has already been called
   * in this tick (in case this is a re-entrant call).
   */
  tick() {
    this._tickCallCount++, this._tickCallCount === 1 && (this.doTick(), this._tickCallCount > 1 && this.tickImmediate(), this._tickCallCount = 0);
  }
  tickImmediate() {
    this.clearNextTick(), this._tickTimer = self.setTimeout(this._boundTick, 0);
  }
  /**
   * For subclass to implement task logic
   * @abstract
   */
  doTick() {
  }
}
class $d {
  constructor(e, t, i, s = 0, n = -1, a = !1) {
    this.level = void 0, this.sn = void 0, this.part = void 0, this.id = void 0, this.size = void 0, this.partial = void 0, this.transmuxing = Jn(), this.buffering = {
      audio: Jn(),
      video: Jn(),
      audiovideo: Jn()
    }, this.level = e, this.sn = t, this.id = i, this.size = s, this.part = n, this.partial = a;
  }
}
function Jn() {
  return {
    start: 0,
    executeStart: 0,
    executeEnd: 0,
    end: 0
  };
}
const up = {
  length: 0,
  start: () => 0,
  end: () => 0
};
class ce {
  /**
   * Return true if `media`'s buffered include `position`
   */
  static isBuffered(e, t) {
    if (e) {
      const i = ce.getBuffered(e);
      for (let s = i.length; s--; )
        if (t >= i.start(s) && t <= i.end(s))
          return !0;
    }
    return !1;
  }
  static bufferedRanges(e) {
    if (e) {
      const t = ce.getBuffered(e);
      return ce.timeRangesToArray(t);
    }
    return [];
  }
  static timeRangesToArray(e) {
    const t = [];
    for (let i = 0; i < e.length; i++)
      t.push({
        start: e.start(i),
        end: e.end(i)
      });
    return t;
  }
  static bufferInfo(e, t, i) {
    if (e) {
      const s = ce.bufferedRanges(e);
      if (s.length)
        return ce.bufferedInfo(s, t, i);
    }
    return {
      len: 0,
      start: t,
      end: t,
      bufferedIndex: -1
    };
  }
  static bufferedInfo(e, t, i) {
    t = Math.max(0, t), e.length > 1 && e.sort((d, h) => d.start - h.start || h.end - d.end);
    let s = -1, n = [];
    if (i)
      for (let d = 0; d < e.length; d++) {
        t >= e[d].start && t <= e[d].end && (s = d);
        const h = n.length;
        if (h) {
          const u = n[h - 1].end;
          e[d].start - u < i ? e[d].end > u && (n[h - 1].end = e[d].end) : n.push(e[d]);
        } else
          n.push(e[d]);
      }
    else
      n = e;
    let a = 0, o, c = t, l = t;
    for (let d = 0; d < n.length; d++) {
      const h = n[d].start, u = n[d].end;
      if (s === -1 && t >= h && t <= u && (s = d), t + i >= h && t < u)
        c = h, l = u, a = l - t;
      else if (t + i < h) {
        o = h;
        break;
      }
    }
    return {
      len: a,
      start: c || 0,
      end: l || 0,
      nextStart: o,
      buffered: e,
      bufferedIndex: s
    };
  }
  /**
   * Safe method to get buffered property.
   * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
   */
  static getBuffered(e) {
    try {
      return e.buffered || up;
    } catch (t) {
      return Pe.log("failed to get media.buffered", t), up;
    }
  }
}
const n_ = /\{\$([a-zA-Z0-9-_]+)\}/g;
function fp(r) {
  return n_.test(r);
}
function wc(r, e) {
  if (r.variableList !== null || r.hasVariableRefs) {
    const t = r.variableList;
    return e.replace(n_, (i) => {
      const s = i.substring(2, i.length - 1), n = t == null ? void 0 : t[s];
      return n === void 0 ? (r.playlistParsingError || (r.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)), i) : n;
    });
  }
  return e;
}
function pp(r, e, t) {
  let i = r.variableList;
  i || (r.variableList = i = {});
  let s, n;
  if ("QUERYPARAM" in e) {
    s = e.QUERYPARAM;
    try {
      const a = new self.URL(t).searchParams;
      if (a.has(s))
        n = a.get(s);
      else
        throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`);
    } catch (a) {
      r.playlistParsingError || (r.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`));
    }
  } else
    s = e.NAME, n = e.VALUE;
  s in i ? r.playlistParsingError || (r.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)) : i[s] = n || "";
}
function MC(r, e, t) {
  const i = e.IMPORT;
  if (t && i in t) {
    let s = r.variableList;
    s || (r.variableList = s = {}), s[i] = t[i];
  } else
    r.playlistParsingError || (r.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`));
}
const BC = /^(\d+)x(\d+)$/, mp = /(.+?)=(".*?"|.*?)(?:,|$)/g;
class $e {
  constructor(e, t) {
    typeof e == "string" && (e = $e.parseAttrList(e, t)), Me(this, e);
  }
  get clientAttrs() {
    return Object.keys(this).filter((e) => e.substring(0, 2) === "X-");
  }
  decimalInteger(e) {
    const t = parseInt(this[e], 10);
    return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t;
  }
  hexadecimalInteger(e) {
    if (this[e]) {
      let t = (this[e] || "0x").slice(2);
      t = (t.length & 1 ? "0" : "") + t;
      const i = new Uint8Array(t.length / 2);
      for (let s = 0; s < t.length / 2; s++)
        i[s] = parseInt(t.slice(s * 2, s * 2 + 2), 16);
      return i;
    }
    return null;
  }
  hexadecimalIntegerAsNumber(e) {
    const t = parseInt(this[e], 16);
    return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t;
  }
  decimalFloatingPoint(e) {
    return parseFloat(this[e]);
  }
  optionalFloat(e, t) {
    const i = this[e];
    return i ? parseFloat(i) : t;
  }
  enumeratedString(e) {
    return this[e];
  }
  enumeratedStringList(e, t) {
    const i = this[e];
    return (i ? i.split(/[ ,]+/) : []).reduce((s, n) => (s[n.toLowerCase()] = !0, s), t);
  }
  bool(e) {
    return this[e] === "YES";
  }
  decimalResolution(e) {
    const t = BC.exec(this[e]);
    if (t !== null)
      return {
        width: parseInt(t[1], 10),
        height: parseInt(t[2], 10)
      };
  }
  static parseAttrList(e, t) {
    let i;
    const s = {}, n = '"';
    for (mp.lastIndex = 0; (i = mp.exec(e)) !== null; ) {
      const a = i[1].trim();
      let o = i[2];
      const c = o.indexOf(n) === 0 && o.lastIndexOf(n) === o.length - 1;
      let l = !1;
      if (c)
        o = o.slice(1, -1);
      else
        switch (a) {
          case "IV":
          case "SCTE35-CMD":
          case "SCTE35-IN":
          case "SCTE35-OUT":
            l = !0;
        }
      if (t && (c || l))
        o = wc(t, o);
      else if (!l && !c)
        switch (a) {
          case "CLOSED-CAPTIONS":
            if (o === "NONE")
              break;
          case "ALLOWED-CPC":
          case "CLASS":
          case "ASSOC-LANGUAGE":
          case "AUDIO":
          case "BYTERANGE":
          case "CHANNELS":
          case "CHARACTERISTICS":
          case "CODECS":
          case "DATA-ID":
          case "END-DATE":
          case "GROUP-ID":
          case "ID":
          case "IMPORT":
          case "INSTREAM-ID":
          case "KEYFORMAT":
          case "KEYFORMATVERSIONS":
          case "LANGUAGE":
          case "NAME":
          case "PATHWAY-ID":
          case "QUERYPARAM":
          case "RECENTLY-REMOVED-DATERANGES":
          case "SERVER-URI":
          case "STABLE-RENDITION-ID":
          case "STABLE-VARIANT-ID":
          case "START-DATE":
          case "SUBTITLES":
          case "SUPPLEMENTAL-CODECS":
          case "URI":
          case "VALUE":
          case "VIDEO":
          case "X-ASSET-LIST":
          case "X-ASSET-URI":
            Pe.warn(`${e}: attribute ${a} is missing quotes`);
        }
      s[a] = o;
    }
    return s;
  }
}
const FC = "com.apple.hls.interstitial";
function OC(r) {
  return r !== "ID" && r !== "CLASS" && r !== "CUE" && r !== "START-DATE" && r !== "DURATION" && r !== "END-DATE" && r !== "END-ON-NEXT";
}
function NC(r) {
  return r === "SCTE35-OUT" || r === "SCTE35-IN" || r === "SCTE35-CMD";
}
class a_ {
  constructor(e, t, i = 0) {
    var s;
    if (this.attr = void 0, this.tagAnchor = void 0, this.tagOrder = void 0, this._startDate = void 0, this._endDate = void 0, this._dateAtEnd = void 0, this._cue = void 0, this._badValueForSameId = void 0, this.tagAnchor = (t == null ? void 0 : t.tagAnchor) || null, this.tagOrder = (s = t == null ? void 0 : t.tagOrder) != null ? s : i, t) {
      const n = t.attr;
      for (const a in n)
        if (Object.prototype.hasOwnProperty.call(e, a) && e[a] !== n[a]) {
          Pe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`), this._badValueForSameId = a;
          break;
        }
      e = Me(new $e({}), n, e);
    }
    if (this.attr = e, t ? (this._startDate = t._startDate, this._cue = t._cue, this._endDate = t._endDate, this._dateAtEnd = t._dateAtEnd) : this._startDate = new Date(e["START-DATE"]), "END-DATE" in this.attr) {
      const n = (t == null ? void 0 : t.endDate) || new Date(this.attr["END-DATE"]);
      q(n.getTime()) && (this._endDate = n);
    }
  }
  get id() {
    return this.attr.ID;
  }
  get class() {
    return this.attr.CLASS;
  }
  get cue() {
    const e = this._cue;
    return e === void 0 ? this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
      pre: !1,
      post: !1,
      once: !1
    }) : e;
  }
  get startTime() {
    const {
      tagAnchor: e
    } = this;
    return e === null || e.programDateTime === null ? (Pe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`), NaN) : e.start + (this.startDate.getTime() - e.programDateTime) / 1e3;
  }
  get startDate() {
    return this._startDate;
  }
  get endDate() {
    const e = this._endDate || this._dateAtEnd;
    if (e)
      return e;
    const t = this.duration;
    return t !== null ? this._dateAtEnd = new Date(this._startDate.getTime() + t * 1e3) : null;
  }
  get duration() {
    if ("DURATION" in this.attr) {
      const e = this.attr.decimalFloatingPoint("DURATION");
      if (q(e))
        return e;
    } else if (this._endDate)
      return (this._endDate.getTime() - this._startDate.getTime()) / 1e3;
    return null;
  }
  get plannedDuration() {
    return "PLANNED-DURATION" in this.attr ? this.attr.decimalFloatingPoint("PLANNED-DURATION") : null;
  }
  get endOnNext() {
    return this.attr.bool("END-ON-NEXT");
  }
  get isInterstitial() {
    return this.class === FC;
  }
  get isValid() {
    return !!this.id && !this._badValueForSameId && q(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || "X-ASSET-URI" in this.attr || "X-ASSET-LIST" in this.attr);
  }
}
const GC = 10;
class UC {
  constructor(e) {
    this.PTSKnown = !1, this.alignedSliding = !1, this.averagetargetduration = void 0, this.endCC = 0, this.endSN = 0, this.fragments = void 0, this.fragmentHint = void 0, this.partList = null, this.dateRanges = void 0, this.dateRangeTagCount = 0, this.live = !0, this.requestScheduled = -1, this.ageHeader = 0, this.advancedDateTime = void 0, this.updated = !0, this.advanced = !0, this.misses = 0, this.startCC = 0, this.startSN = 0, this.startTimeOffset = null, this.targetduration = 0, this.totalduration = 0, this.type = null, this.url = void 0, this.m3u8 = "", this.version = null, this.canBlockReload = !1, this.canSkipUntil = 0, this.canSkipDateRanges = !1, this.skippedSegments = 0, this.recentlyRemovedDateranges = void 0, this.partHoldBack = 0, this.holdBack = 0, this.partTarget = 0, this.preloadHint = void 0, this.renditionReports = void 0, this.tuneInGoal = 0, this.deltaUpdateFailed = void 0, this.driftStartTime = 0, this.driftEndTime = 0, this.driftStart = 0, this.driftEnd = 0, this.encryptedFragments = void 0, this.playlistParsingError = null, this.variableList = null, this.hasVariableRefs = !1, this.appliedTimelineOffset = void 0, this.fragments = [], this.encryptedFragments = [], this.dateRanges = {}, this.url = e;
  }
  reloaded(e) {
    if (!e) {
      this.advanced = !0, this.updated = !0;
      return;
    }
    const t = this.lastPartSn - e.lastPartSn, i = this.lastPartIndex - e.lastPartIndex;
    this.updated = this.endSN !== e.endSN || !!i || !!t || !this.live, this.advanced = this.endSN > e.endSN || t > 0 || t === 0 && i > 0, this.updated || this.advanced ? this.misses = Math.floor(e.misses * 0.6) : this.misses = e.misses + 1;
  }
  hasKey(e) {
    return this.encryptedFragments.some((t) => {
      let i = t.decryptdata;
      return i || (t.setKeyFormat(e.keyFormat), i = t.decryptdata), !!i && e.matches(i);
    });
  }
  get hasProgramDateTime() {
    return this.fragments.length ? q(this.fragments[this.fragments.length - 1].programDateTime) : !1;
  }
  get levelTargetDuration() {
    return this.averagetargetduration || this.targetduration || GC;
  }
  get drift() {
    const e = this.driftEndTime - this.driftStartTime;
    return e > 0 ? (this.driftEnd - this.driftStart) * 1e3 / e : 1;
  }
  get edge() {
    return this.partEnd || this.fragmentEnd;
  }
  get partEnd() {
    var e;
    return (e = this.partList) != null && e.length ? this.partList[this.partList.length - 1].end : this.fragmentEnd;
  }
  get fragmentEnd() {
    return this.fragments.length ? this.fragments[this.fragments.length - 1].end : 0;
  }
  get fragmentStart() {
    return this.fragments.length ? this.fragments[0].start : 0;
  }
  get age() {
    return this.advancedDateTime ? Math.max(Date.now() - this.advancedDateTime, 0) / 1e3 : 0;
  }
  get lastPartIndex() {
    var e;
    return (e = this.partList) != null && e.length ? this.partList[this.partList.length - 1].index : -1;
  }
  get maxPartIndex() {
    const e = this.partList;
    if (e) {
      const t = this.lastPartIndex;
      if (t !== -1) {
        for (let i = e.length; i--; )
          if (e[i].index > t)
            return e[i].index;
        return t;
      }
    }
    return 0;
  }
  get lastPartSn() {
    var e;
    return (e = this.partList) != null && e.length ? this.partList[this.partList.length - 1].fragment.sn : this.endSN;
  }
  get expired() {
    if (this.live && this.age && this.misses < 3) {
      const e = this.partEnd - this.fragmentStart;
      return this.age > Math.max(e, this.totalduration) + this.levelTargetDuration;
    }
    return !1;
  }
}
function o_(r, e) {
  return r.length === e.length ? !r.some((t, i) => t !== e[i]) : !1;
}
function gp(r, e) {
  return !r && !e ? !0 : !r || !e ? !1 : o_(r, e);
}
function br(r) {
  return r === "AES-128" || r === "AES-256" || r === "AES-256-CTR";
}
function Kd(r) {
  switch (r) {
    case "AES-128":
    case "AES-256":
      return xs.cbc;
    case "AES-256-CTR":
      return xs.ctr;
    default:
      throw new Error(`invalid full segment method ${r}`);
  }
}
function Xd(r) {
  return Uint8Array.from(atob(r), (e) => e.charCodeAt(0));
}
function Mc(r) {
  return Uint8Array.from(unescape(encodeURIComponent(r)), (e) => e.charCodeAt(0));
}
function VC(r) {
  const e = Mc(r).subarray(0, 16), t = new Uint8Array(16);
  return t.set(e, 16 - e.length), t;
}
function WC(r) {
  const e = function(i, s, n) {
    const a = i[s];
    i[s] = i[n], i[n] = a;
  };
  e(r, 0, 3), e(r, 1, 2), e(r, 4, 5), e(r, 6, 7);
}
function HC(r) {
  const e = r.split(":");
  let t = null;
  if (e[0] === "data" && e.length === 2) {
    const i = e[1].split(";"), s = i[i.length - 1].split(",");
    if (s.length === 2) {
      const n = s[0] === "base64", a = s[1];
      n ? (i.splice(-1, 1), t = Xd(a)) : t = VC(a);
    }
  }
  return t;
}
const ao = typeof self < "u" ? self : void 0;
var Qe = {
  CLEARKEY: "org.w3.clearkey",
  FAIRPLAY: "com.apple.fps",
  PLAYREADY: "com.microsoft.playready",
  WIDEVINE: "com.widevine.alpha"
}, kt = {
  CLEARKEY: "org.w3.clearkey",
  FAIRPLAY: "com.apple.streamingkeydelivery",
  PLAYREADY: "com.microsoft.playready",
  WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
};
function Pa(r) {
  switch (r) {
    case kt.FAIRPLAY:
      return Qe.FAIRPLAY;
    case kt.PLAYREADY:
      return Qe.PLAYREADY;
    case kt.WIDEVINE:
      return Qe.WIDEVINE;
    case kt.CLEARKEY:
      return Qe.CLEARKEY;
  }
}
function v0(r) {
  switch (r) {
    case Qe.FAIRPLAY:
      return kt.FAIRPLAY;
    case Qe.PLAYREADY:
      return kt.PLAYREADY;
    case Qe.WIDEVINE:
      return kt.WIDEVINE;
    case Qe.CLEARKEY:
      return kt.CLEARKEY;
  }
}
function qr(r) {
  const {
    drmSystems: e,
    widevineLicenseUrl: t
  } = r, i = e ? [Qe.FAIRPLAY, Qe.WIDEVINE, Qe.PLAYREADY, Qe.CLEARKEY].filter((s) => !!e[s]) : [];
  return !i[Qe.WIDEVINE] && t && i.push(Qe.WIDEVINE), i;
}
const l_ = function(r) {
  return ao != null && (r = ao.navigator) != null && r.requestMediaKeySystemAccess ? self.navigator.requestMediaKeySystemAccess.bind(self.navigator) : null;
}();
function ZC(r, e, t, i) {
  let s;
  switch (r) {
    case Qe.FAIRPLAY:
      s = ["cenc", "sinf"];
      break;
    case Qe.WIDEVINE:
    case Qe.PLAYREADY:
      s = ["cenc"];
      break;
    case Qe.CLEARKEY:
      s = ["cenc", "keyids"];
      break;
    default:
      throw new Error(`Unknown key-system: ${r}`);
  }
  return $C(s, e, t, i);
}
function $C(r, e, t, i) {
  return [{
    initDataTypes: r,
    persistentState: i.persistentState || "optional",
    distinctiveIdentifier: i.distinctiveIdentifier || "optional",
    sessionTypes: i.sessionTypes || [i.sessionType || "temporary"],
    audioCapabilities: e.map((n) => ({
      contentType: `audio/mp4; codecs=${n}`,
      robustness: i.audioRobustness || "",
      encryptionScheme: i.audioEncryptionScheme || null
    })),
    videoCapabilities: t.map((n) => ({
      contentType: `video/mp4; codecs=${n}`,
      robustness: i.videoRobustness || "",
      encryptionScheme: i.videoEncryptionScheme || null
    }))
  }];
}
function KC(r) {
  var e;
  return !!r && (r.sessionType === "persistent-license" || !!((e = r.sessionTypes) != null && e.some((t) => t === "persistent-license")));
}
function XC(r) {
  const e = new Uint16Array(r.buffer, r.byteOffset, r.byteLength / 2), t = String.fromCharCode.apply(null, Array.from(e)), i = t.substring(t.indexOf("<"), t.length), a = new DOMParser().parseFromString(i, "text/xml").getElementsByTagName("KID")[0];
  if (a) {
    const o = a.childNodes[0] ? a.childNodes[0].nodeValue : a.getAttribute("VALUE");
    if (o) {
      const c = Xd(o).subarray(0, 16);
      return WC(c), c;
    }
  }
  return null;
}
let qn = {};
class Io {
  static clearKeyUriToKeyIdMap() {
    qn = {};
  }
  constructor(e, t, i, s = [1], n = null, a) {
    this.uri = void 0, this.method = void 0, this.keyFormat = void 0, this.keyFormatVersions = void 0, this.encrypted = void 0, this.isCommonEncryption = void 0, this.iv = null, this.key = null, this.keyId = null, this.pssh = null, this.method = e, this.uri = t, this.keyFormat = i, this.keyFormatVersions = s, this.iv = n, this.encrypted = e ? e !== "NONE" : !1, this.isCommonEncryption = this.encrypted && !br(e), a != null && a.startsWith("0x") && (this.keyId = new Uint8Array(Vg(a)));
  }
  matches(e) {
    return e.uri === this.uri && e.method === this.method && e.encrypted === this.encrypted && e.keyFormat === this.keyFormat && o_(e.keyFormatVersions, this.keyFormatVersions) && gp(e.iv, this.iv) && gp(e.keyId, this.keyId);
  }
  isSupported() {
    if (this.method) {
      if (br(this.method) || this.method === "NONE")
        return !0;
      if (this.keyFormat === "identity")
        return this.method === "SAMPLE-AES";
      switch (this.keyFormat) {
        case kt.FAIRPLAY:
        case kt.WIDEVINE:
        case kt.PLAYREADY:
        case kt.CLEARKEY:
          return ["SAMPLE-AES", "SAMPLE-AES-CENC", "SAMPLE-AES-CTR"].indexOf(this.method) !== -1;
      }
    }
    return !1;
  }
  getDecryptData(e) {
    if (!this.encrypted || !this.uri)
      return null;
    if (br(this.method) && this.uri && !this.iv) {
      typeof e != "number" && (Pe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`), e = 0);
      const i = YC(e);
      return new Io(this.method, this.uri, "identity", this.keyFormatVersions, i);
    }
    if (this.pssh && this.keyId)
      return this;
    const t = HC(this.uri);
    if (t)
      switch (this.keyFormat) {
        case kt.WIDEVINE:
          if (this.pssh = t, !this.keyId && t.length >= 22) {
            const i = t.length - 22;
            this.keyId = t.subarray(i, i + 16);
          }
          break;
        case kt.PLAYREADY: {
          const i = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]);
          this.pssh = j4(i, null, t), this.keyId = XC(t);
          break;
        }
        default: {
          let i = t.subarray(0, 16);
          if (i.length !== 16) {
            const s = new Uint8Array(16);
            s.set(i, 16 - i.length), i = s;
          }
          this.keyId = i;
          break;
        }
      }
    if (!this.keyId || this.keyId.byteLength !== 16) {
      let i = qn[this.uri];
      if (!i) {
        const s = Object.keys(qn).length % Number.MAX_SAFE_INTEGER;
        i = new Uint8Array(16), new DataView(i.buffer, 12, 4).setUint32(0, s), qn[this.uri] = i;
      }
      this.keyId = i;
    }
    return this;
  }
}
function YC(r) {
  const e = new Uint8Array(16);
  for (let t = 12; t < 16; t++)
    e[t] = r >> 8 * (15 - t) & 255;
  return e;
}
const _p = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g, yp = /#EXT-X-MEDIA:(.*)/g, zC = /^#EXT(?:INF|-X-TARGETDURATION):/m, E0 = new RegExp([
  /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  /(?!#) *(\S[^\r\n]*)/.source,
  // segment URI, group 3 => the URI (note newline is not eaten)
  /#.*/.source
  // All other non-segment oriented tags will match with all groups empty
].join("|"), "g"), jC = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join("|"));
class Pi {
  static findGroup(e, t) {
    for (let i = 0; i < e.length; i++) {
      const s = e[i];
      if (s.id === t)
        return s;
    }
  }
  static resolve(e, t) {
    return Nd.buildAbsoluteURL(t, e, {
      alwaysNormalize: !0
    });
  }
  static isMediaPlaylist(e) {
    return zC.test(e);
  }
  static parseMasterPlaylist(e, t) {
    const i = fp(e), s = {
      contentSteering: null,
      levels: [],
      playlistParsingError: null,
      sessionData: null,
      sessionKeys: null,
      startTimeOffset: null,
      variableList: null,
      hasVariableRefs: i
    }, n = [];
    _p.lastIndex = 0;
    let a;
    for (; (a = _p.exec(e)) != null; )
      if (a[1]) {
        var o;
        const l = new $e(a[1], s), d = wc(s, a[2]), h = {
          attrs: l,
          bitrate: l.decimalInteger("BANDWIDTH") || l.decimalInteger("AVERAGE-BANDWIDTH"),
          name: l.NAME,
          url: Pi.resolve(d, t)
        }, u = l.decimalResolution("RESOLUTION");
        u && (h.width = u.width, h.height = u.height), Ep(l.CODECS, h);
        const f = l["SUPPLEMENTAL-CODECS"];
        f && (h.supplemental = {}, Ep(f, h.supplemental)), (o = h.unknownCodecs) != null && o.length || n.push(h), s.levels.push(h);
      } else if (a[3]) {
        const l = a[3], d = a[4];
        switch (l) {
          case "SESSION-DATA": {
            const h = new $e(d, s), u = h["DATA-ID"];
            u && (s.sessionData === null && (s.sessionData = {}), s.sessionData[u] = h);
            break;
          }
          case "SESSION-KEY": {
            const h = xp(d, t, s);
            h.encrypted && h.isSupported() ? (s.sessionKeys === null && (s.sessionKeys = []), s.sessionKeys.push(h)) : Pe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);
            break;
          }
          case "DEFINE": {
            {
              const h = new $e(d, s);
              pp(s, h, t);
            }
            break;
          }
          case "CONTENT-STEERING": {
            const h = new $e(d, s);
            s.contentSteering = {
              uri: Pi.resolve(h["SERVER-URI"], t),
              pathwayId: h["PATHWAY-ID"] || "."
            };
            break;
          }
          case "START": {
            s.startTimeOffset = vp(d);
            break;
          }
        }
      }
    const c = n.length > 0 && n.length < s.levels.length;
    return s.levels = c ? n : s.levels, s.levels.length === 0 && (s.playlistParsingError = new Error("no levels found in manifest")), s;
  }
  static parseMasterPlaylistMedia(e, t, i) {
    let s;
    const n = {}, a = i.levels, o = {
      AUDIO: a.map((l) => ({
        id: l.attrs.AUDIO,
        audioCodec: l.audioCodec
      })),
      SUBTITLES: a.map((l) => ({
        id: l.attrs.SUBTITLES,
        textCodec: l.textCodec
      })),
      "CLOSED-CAPTIONS": []
    };
    let c = 0;
    for (yp.lastIndex = 0; (s = yp.exec(e)) !== null; ) {
      const l = new $e(s[1], i), d = l.TYPE;
      if (d) {
        const h = o[d], u = n[d] || [];
        n[d] = u;
        const f = l.LANGUAGE, p = l["ASSOC-LANGUAGE"], m = l.CHANNELS, g = l.CHARACTERISTICS, x = l["INSTREAM-ID"], _ = {
          attrs: l,
          bitrate: 0,
          id: c++,
          groupId: l["GROUP-ID"] || "",
          name: l.NAME || f || "",
          type: d,
          default: l.bool("DEFAULT"),
          autoselect: l.bool("AUTOSELECT"),
          forced: l.bool("FORCED"),
          lang: f,
          url: l.URI ? Pi.resolve(l.URI, t) : ""
        };
        if (p && (_.assocLang = p), m && (_.channels = m), g && (_.characteristics = g), x && (_.instreamId = x), h != null && h.length) {
          const v = Pi.findGroup(h, _.groupId) || h[0];
          Sp(_, v, "audioCodec"), Sp(_, v, "textCodec");
        }
        u.push(_);
      }
    }
    return n;
  }
  static parseLevelPlaylist(e, t, i, s, n, a) {
    var o;
    const c = {
      url: t
    }, l = new UC(t), d = l.fragments, h = [];
    let u = null, f = 0, p = 0, m = 0, g = 0, x = 0, _ = null, v = new _0(s, c), E, b, A, C = -1, I = !1, L = null, R;
    if (E0.lastIndex = 0, l.m3u8 = e, l.hasVariableRefs = fp(e), ((o = E0.exec(e)) == null ? void 0 : o[0]) !== "#EXTM3U")
      return l.playlistParsingError = new Error("Missing format identifier #EXTM3U"), l;
    for (; (E = E0.exec(e)) !== null; ) {
      I && (I = !1, v = new _0(s, c), v.playlistOffset = m, v.setStart(m), v.sn = f, v.cc = g, x && (v.bitrate = x), v.level = i, u && (v.initSegment = u, u.rawProgramDateTime && (v.rawProgramDateTime = u.rawProgramDateTime, u.rawProgramDateTime = null), L && (v.setByteRange(L), L = null)));
      const N = E[1];
      if (N) {
        v.duration = parseFloat(N);
        const H = (" " + E[2]).slice(1);
        v.title = H || null, v.tagList.push(H ? ["INF", N, H] : ["INF", N]);
      } else if (E[3]) {
        if (q(v.duration)) {
          v.playlistOffset = m, v.setStart(m), A && bp(v, A, l), v.sn = f, v.level = i, v.cc = g, d.push(v);
          const H = (" " + E[3]).slice(1);
          v.relurl = wc(l, H), Bc(v, _, h), _ = v, m += v.duration, f++, p = 0, I = !0;
        }
      } else {
        if (E = E[0].match(jC), !E) {
          Pe.warn("No matches on slow regex match for level playlist!");
          continue;
        }
        for (b = 1; b < E.length && E[b] === void 0; b++)
          ;
        const H = (" " + E[b]).slice(1), G = (" " + E[b + 1]).slice(1), Z = E[b + 2] ? (" " + E[b + 2]).slice(1) : null;
        switch (H) {
          case "BYTERANGE":
            _ ? v.setByteRange(G, _) : v.setByteRange(G);
            break;
          case "PROGRAM-DATE-TIME":
            v.rawProgramDateTime = G, v.tagList.push(["PROGRAM-DATE-TIME", G]), C === -1 && (C = d.length);
            break;
          case "PLAYLIST-TYPE":
            l.type && Ni(l, H, E), l.type = G.toUpperCase();
            break;
          case "MEDIA-SEQUENCE":
            l.startSN !== 0 ? Ni(l, H, E) : d.length > 0 && Ap(l, H, E), f = l.startSN = parseInt(G);
            break;
          case "SKIP": {
            l.skippedSegments && Ni(l, H, E);
            const $ = new $e(G, l), Y = $.decimalInteger("SKIPPED-SEGMENTS");
            if (q(Y)) {
              l.skippedSegments += Y;
              for (let k = Y; k--; )
                d.push(null);
              f += Y;
            }
            const W = $.enumeratedString("RECENTLY-REMOVED-DATERANGES");
            W && (l.recentlyRemovedDateranges = (l.recentlyRemovedDateranges || []).concat(W.split("	")));
            break;
          }
          case "TARGETDURATION":
            l.targetduration !== 0 && Ni(l, H, E), l.targetduration = Math.max(parseInt(G), 1);
            break;
          case "VERSION":
            l.version !== null && Ni(l, H, E), l.version = parseInt(G);
            break;
          case "INDEPENDENT-SEGMENTS":
            break;
          case "ENDLIST":
            l.live || Ni(l, H, E), l.live = !1;
            break;
          case "#":
            (G || Z) && v.tagList.push(Z ? [G, Z] : [G]);
            break;
          case "DISCONTINUITY":
            g++, v.tagList.push(["DIS"]);
            break;
          case "GAP":
            v.gap = !0, v.tagList.push([H]);
            break;
          case "BITRATE":
            v.tagList.push([H, G]), x = parseInt(G) * 1e3, q(x) ? v.bitrate = x : x = 0;
            break;
          case "DATERANGE": {
            const $ = new $e(G, l), Y = new a_($, l.dateRanges[$.ID], l.dateRangeTagCount);
            l.dateRangeTagCount++, Y.isValid || l.skippedSegments ? l.dateRanges[Y.id] = Y : Pe.warn(`Ignoring invalid DATERANGE tag: "${G}"`), v.tagList.push(["EXT-X-DATERANGE", G]);
            break;
          }
          case "DEFINE": {
            {
              const $ = new $e(G, l);
              "IMPORT" in $ ? MC(l, $, a) : pp(l, $, t);
            }
            break;
          }
          case "DISCONTINUITY-SEQUENCE":
            l.startCC !== 0 ? Ni(l, H, E) : d.length > 0 && Ap(l, H, E), l.startCC = g = parseInt(G);
            break;
          case "KEY": {
            const $ = xp(G, t, l);
            if ($.isSupported()) {
              if ($.method === "NONE") {
                A = void 0;
                break;
              }
              A || (A = {});
              const Y = A[$.keyFormat];
              Y != null && Y.matches($) || (Y && (A = Me({}, A)), A[$.keyFormat] = $);
            } else
              Pe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${G}"`);
            break;
          }
          case "START":
            l.startTimeOffset = vp(G);
            break;
          case "MAP": {
            const $ = new $e(G, l);
            if (v.duration) {
              const Y = new _0(s, c);
              Tp(Y, $, i, A), u = Y, v.initSegment = u, u.rawProgramDateTime && !v.rawProgramDateTime && (v.rawProgramDateTime = u.rawProgramDateTime);
            } else {
              const Y = v.byteRangeEndOffset;
              if (Y) {
                const W = v.byteRangeStartOffset;
                L = `${Y - W}@${W}`;
              } else
                L = null;
              Tp(v, $, i, A), u = v, I = !0;
            }
            u.cc = g;
            break;
          }
          case "SERVER-CONTROL": {
            R && Ni(l, H, E), R = new $e(G), l.canBlockReload = R.bool("CAN-BLOCK-RELOAD"), l.canSkipUntil = R.optionalFloat("CAN-SKIP-UNTIL", 0), l.canSkipDateRanges = l.canSkipUntil > 0 && R.bool("CAN-SKIP-DATERANGES"), l.partHoldBack = R.optionalFloat("PART-HOLD-BACK", 0), l.holdBack = R.optionalFloat("HOLD-BACK", 0);
            break;
          }
          case "PART-INF": {
            l.partTarget && Ni(l, H, E);
            const $ = new $e(G);
            l.partTarget = $.decimalFloatingPoint("PART-TARGET");
            break;
          }
          case "PART": {
            let $ = l.partList;
            $ || ($ = l.partList = []);
            const Y = p > 0 ? $[$.length - 1] : void 0, W = p++, k = new $e(G, l), P = new O4(k, v, c, W, Y);
            $.push(P), v.duration += P.duration;
            break;
          }
          case "PRELOAD-HINT": {
            const $ = new $e(G, l);
            l.preloadHint = $;
            break;
          }
          case "RENDITION-REPORT": {
            const $ = new $e(G, l);
            l.renditionReports = l.renditionReports || [], l.renditionReports.push($);
            break;
          }
          default:
            Pe.warn(`line parsed but not handled: ${E}`);
            break;
        }
      }
    }
    _ && !_.relurl ? (d.pop(), m -= _.duration, l.partList && (l.fragmentHint = _)) : l.partList && (Bc(v, _, h), v.cc = g, l.fragmentHint = v, A && bp(v, A, l)), l.targetduration || (l.playlistParsingError = new Error("#EXT-X-TARGETDURATION is required"));
    const D = d.length, M = d[0], w = d[D - 1];
    if (m += l.skippedSegments * l.targetduration, m > 0 && D && w) {
      l.averagetargetduration = m / D;
      const N = w.sn;
      l.endSN = N !== "initSegment" ? N : 0, l.live || (w.endList = !0), C > 0 && (JC(d, C), M && h.unshift(M));
    }
    return l.fragmentHint && (m += l.fragmentHint.duration), l.totalduration = m, h.length && l.dateRangeTagCount && M && c_(h, l), l.endCC = g, l;
  }
}
function c_(r, e) {
  let t = r.length;
  if (!t)
    if (e.hasProgramDateTime) {
      const o = e.fragments[e.fragments.length - 1];
      r.push(o), t++;
    } else
      return;
  const i = r[t - 1], s = e.live ? 1 / 0 : e.totalduration, n = Object.keys(e.dateRanges);
  for (let o = n.length; o--; ) {
    const c = e.dateRanges[n[o]], l = c.startDate.getTime();
    c.tagAnchor = i.ref;
    for (let d = t; d--; ) {
      var a;
      if (((a = r[d]) == null ? void 0 : a.sn) < e.startSN)
        break;
      const h = QC(e, l, r, d, s);
      if (h !== -1) {
        c.tagAnchor = e.fragments[h].ref;
        break;
      }
    }
  }
}
function QC(r, e, t, i, s) {
  const n = t[i];
  if (n) {
    const o = n.programDateTime;
    if (e >= o || i === 0) {
      var a;
      const c = (((a = t[i + 1]) == null ? void 0 : a.start) || s) - n.start;
      if (e <= o + c * 1e3) {
        const l = t[i].sn - r.startSN;
        if (l < 0)
          return -1;
        const d = r.fragments;
        if (d.length > t.length) {
          const u = (t[i + 1] || d[d.length - 1]).sn - r.startSN;
          for (let f = u; f > l; f--) {
            const p = d[f].programDateTime;
            if (e >= p && e < p + d[f].duration * 1e3)
              return f;
          }
        }
        return l;
      }
    }
  }
  return -1;
}
function xp(r, e, t) {
  var i, s;
  const n = new $e(r, t), a = (i = n.METHOD) != null ? i : "", o = n.URI, c = n.hexadecimalInteger("IV"), l = n.KEYFORMATVERSIONS, d = (s = n.KEYFORMAT) != null ? s : "identity";
  o && n.IV && !c && Pe.error(`Invalid IV: ${n.IV}`);
  const h = o ? Pi.resolve(o, e) : "", u = (l || "1").split("/").map(Number).filter(Number.isFinite);
  return new Io(a, h, d, u, c, n.KEYID);
}
function vp(r) {
  const t = new $e(r).decimalFloatingPoint("TIME-OFFSET");
  return q(t) ? t : null;
}
function Ep(r, e) {
  let t = (r || "").split(/[ ,]+/).filter((i) => i);
  ["video", "audio", "text"].forEach((i) => {
    const s = t.filter((n) => Vd(n, i));
    s.length && (e[`${i}Codec`] = s.map((n) => n.split("/")[0]).join(","), t = t.filter((n) => s.indexOf(n) === -1));
  }), e.unknownCodecs = t;
}
function Sp(r, e, t) {
  const i = e[t];
  i && (r[t] = i);
}
function JC(r, e) {
  let t = r[e];
  for (let i = e; i--; ) {
    const s = r[i];
    if (!s)
      return;
    s.programDateTime = t.programDateTime - s.duration * 1e3, t = s;
  }
}
function Bc(r, e, t) {
  r.rawProgramDateTime ? t.push(r) : e != null && e.programDateTime && (r.programDateTime = e.endProgramDateTime);
}
function Tp(r, e, t, i) {
  r.relurl = e.URI, e.BYTERANGE && r.setByteRange(e.BYTERANGE), r.level = t, r.sn = "initSegment", i && (r.levelkeys = i), r.initSegment = null;
}
function bp(r, e, t) {
  r.levelkeys = e;
  const {
    encryptedFragments: i
  } = t;
  (!i.length || i[i.length - 1].levelkeys !== e) && Object.keys(e).some((s) => e[s].isCommonEncryption) && i.push(r);
}
function Ni(r, e, t) {
  r.playlistParsingError = new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`);
}
function Ap(r, e, t) {
  r.playlistParsingError = new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`);
}
function S0(r, e) {
  const t = e.startPTS;
  if (q(t)) {
    let i = 0, s;
    e.sn > r.sn ? (i = t - r.start, s = r) : (i = r.start - t, s = e), s.duration !== i && s.setDuration(i);
  } else e.sn > r.sn ? r.cc === e.cc && r.minEndPTS ? e.setStart(r.start + (r.minEndPTS - r.start)) : e.setStart(r.start + r.duration) : e.setStart(Math.max(r.start - e.duration, 0));
}
function d_(r, e, t, i, s, n, a) {
  i - t <= 0 && (a.warn("Fragment should have a positive duration", e), i = t + e.duration, n = s + e.duration);
  let c = t, l = i;
  const d = e.startPTS, h = e.endPTS;
  if (q(d)) {
    const x = Math.abs(d - t);
    r && x > r.totalduration ? a.warn(`media timestamps and playlist times differ by ${x}s for level ${e.level} ${r.url}`) : q(e.deltaPTS) ? e.deltaPTS = Math.max(x, e.deltaPTS) : e.deltaPTS = x, c = Math.max(t, d), t = Math.min(t, d), s = e.startDTS !== void 0 ? Math.min(s, e.startDTS) : s, l = Math.min(i, h), i = Math.max(i, h), n = e.endDTS !== void 0 ? Math.max(n, e.endDTS) : n;
  }
  const u = t - e.start;
  e.start !== 0 && e.setStart(t), e.setDuration(i - e.start), e.startPTS = t, e.maxStartPTS = c, e.startDTS = s, e.endPTS = i, e.minEndPTS = l, e.endDTS = n;
  const f = e.sn;
  if (!r || f < r.startSN || f > r.endSN)
    return 0;
  let p;
  const m = f - r.startSN, g = r.fragments;
  for (g[m] = e, p = m; p > 0; p--)
    S0(g[p], g[p - 1]);
  for (p = m; p < g.length - 1; p++)
    S0(g[p], g[p + 1]);
  return r.fragmentHint && S0(g[g.length - 1], r.fragmentHint), r.PTSKnown = r.alignedSliding = !0, u;
}
function qC(r, e, t) {
  if (r === e)
    return;
  let i = null;
  const s = r.fragments;
  for (let d = s.length - 1; d >= 0; d--) {
    const h = s[d].initSegment;
    if (h) {
      i = h;
      break;
    }
  }
  r.fragmentHint && delete r.fragmentHint.endPTS;
  let n;
  i8(r, e, (d, h, u, f) => {
    if ((!e.startCC || e.skippedSegments) && h.cc !== d.cc) {
      const p = d.cc - h.cc;
      for (let m = u; m < f.length; m++)
        f[m].cc += p;
      e.endCC = f[f.length - 1].cc;
    }
    q(d.startPTS) && q(d.endPTS) && (h.setStart(h.startPTS = d.startPTS), h.startDTS = d.startDTS, h.maxStartPTS = d.maxStartPTS, h.endPTS = d.endPTS, h.endDTS = d.endDTS, h.minEndPTS = d.minEndPTS, h.setDuration(d.endPTS - d.startPTS), h.duration && (n = h), e.PTSKnown = e.alignedSliding = !0), d.hasStreams && (h.elementaryStreams = d.elementaryStreams), h.loader = d.loader, d.hasStats && (h.stats = d.stats), d.initSegment && (h.initSegment = d.initSegment, i = d.initSegment);
  });
  const a = e.fragments, o = e.fragmentHint ? a.concat(e.fragmentHint) : a;
  if (i && o.forEach((d) => {
    var h;
    d && (!d.initSegment || d.initSegment.relurl === ((h = i) == null ? void 0 : h.relurl)) && (d.initSegment = i);
  }), e.skippedSegments) {
    if (e.deltaUpdateFailed = a.some((d) => !d), e.deltaUpdateFailed) {
      t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
      for (let d = e.skippedSegments; d--; )
        a.shift();
      e.startSN = a[0].sn;
    } else {
      e.canSkipDateRanges && (e.dateRanges = e8(r.dateRanges, e, t));
      const d = r.fragments.filter((h) => h.rawProgramDateTime);
      if (r.hasProgramDateTime && !e.hasProgramDateTime)
        for (let h = 1; h < o.length; h++)
          o[h].programDateTime === null && Bc(o[h], o[h - 1], d);
      c_(d, e);
    }
    e.endCC = a[a.length - 1].cc;
  }
  if (!e.startCC) {
    var c;
    const d = f_(r, e.startSN - 1);
    e.startCC = (c = d == null ? void 0 : d.cc) != null ? c : a[0].cc;
  }
  t8(r.partList, e.partList, (d, h) => {
    h.elementaryStreams = d.elementaryStreams, h.stats = d.stats;
  }), n ? d_(e, n, n.startPTS, n.endPTS, n.startDTS, n.endDTS, t) : h_(r, e), a.length && (e.totalduration = e.edge - a[0].start), e.driftStartTime = r.driftStartTime, e.driftStart = r.driftStart;
  const l = e.advancedDateTime;
  if (e.advanced && l) {
    const d = e.edge;
    e.driftStart || (e.driftStartTime = l, e.driftStart = d), e.driftEndTime = l, e.driftEnd = d;
  } else
    e.driftEndTime = r.driftEndTime, e.driftEnd = r.driftEnd, e.advancedDateTime = r.advancedDateTime;
  e.requestScheduled === -1 && (e.requestScheduled = r.requestScheduled);
}
function e8(r, e, t) {
  const {
    dateRanges: i,
    recentlyRemovedDateranges: s
  } = e, n = Me({}, r);
  s && s.forEach((c) => {
    delete n[c];
  });
  const o = Object.keys(n).length;
  return o ? (Object.keys(i).forEach((c) => {
    const l = n[c], d = new a_(i[c].attr, l);
    d.isValid ? (n[c] = d, l || (d.tagOrder += o)) : t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ze(i[c].attr)}"`);
  }), n) : i;
}
function t8(r, e, t) {
  if (r && e) {
    let i = 0;
    for (let s = 0, n = r.length; s <= n; s++) {
      const a = r[s], o = e[s + i];
      a && o && a.index === o.index && a.fragment.sn === o.fragment.sn ? t(a, o) : i--;
    }
  }
}
function i8(r, e, t) {
  const i = e.skippedSegments, s = Math.max(r.startSN, e.startSN) - e.startSN, n = (r.fragmentHint ? 1 : 0) + (i ? e.endSN : Math.min(r.endSN, e.endSN)) - e.startSN, a = e.startSN - r.startSN, o = e.fragmentHint ? e.fragments.concat(e.fragmentHint) : e.fragments, c = r.fragmentHint ? r.fragments.concat(r.fragmentHint) : r.fragments;
  for (let l = s; l <= n; l++) {
    const d = c[a + l];
    let h = o[l];
    if (i && !h && d && (h = e.fragments[l] = d), d && h) {
      t(d, h, l, o);
      const u = d.relurl, f = h.relurl;
      if (u && s8(u, f)) {
        e.playlistParsingError = Cp(`media sequence mismatch ${h.sn}:`, r, e, d, h);
        return;
      } else if (d.cc !== h.cc) {
        e.playlistParsingError = Cp(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`, r, e, d, h);
        return;
      }
    }
  }
}
function Cp(r, e, t, i, s) {
  return new Error(`${r} ${s.url}
Playlist starting @${e.startSN}
${e.m3u8}

Playlist starting @${t.startSN}
${t.m3u8}`);
}
function h_(r, e, t = !0) {
  const i = e.startSN + e.skippedSegments - r.startSN, s = r.fragments, n = i >= 0;
  let a = 0;
  if (n && i < s.length)
    a = s[i].start;
  else if (n && e.startSN === r.endSN + 1)
    a = r.fragmentEnd;
  else if (n && t)
    a = r.fragmentStart + i * e.levelTargetDuration;
  else if (!e.skippedSegments && e.fragmentStart === 0)
    a = r.fragmentStart;
  else
    return;
  Fc(e, a);
}
function Fc(r, e) {
  if (e) {
    const t = r.fragments;
    for (let i = r.skippedSegments; i < t.length; i++)
      t[i].addStart(e);
    r.fragmentHint && r.fragmentHint.addStart(e);
  }
}
function u_(r, e = 1 / 0) {
  let t = 1e3 * r.targetduration;
  if (r.updated) {
    const i = r.fragments;
    if (i.length && t * 4 > e) {
      const n = i[i.length - 1].duration * 1e3;
      n < t && (t = n);
    }
  } else
    t /= 2;
  return Math.round(t);
}
function f_(r, e, t) {
  if (!r)
    return null;
  let i = r.fragments[e - r.startSN];
  return i || (i = r.fragmentHint, i && i.sn === e) ? i : e < r.startSN && t && t.sn === e ? t : null;
}
function Rp(r, e, t) {
  return r ? p_(r.partList, e, t) : null;
}
function p_(r, e, t) {
  if (r)
    for (let i = r.length; i--; ) {
      const s = r[i];
      if (s.index === t && s.fragment.sn === e)
        return s;
    }
  return null;
}
function m_(r) {
  r.forEach((e, t) => {
    var i;
    (i = e.details) == null || i.fragments.forEach((s) => {
      s.level = t, s.initSegment && (s.initSegment.level = t);
    });
  });
}
function s8(r, e) {
  return r !== e && e ? Ip(r) !== Ip(e) : !1;
}
function Ip(r) {
  return r.replace(/\?[^?]*$/, "");
}
function ln(r, e) {
  for (let i = 0, s = r.length; i < s; i++) {
    var t;
    if (((t = r[i]) == null ? void 0 : t.cc) === e)
      return r[i];
  }
  return null;
}
function r8(r, e) {
  return !!(r && e.startCC < r.endCC && e.endCC > r.startCC);
}
function Lp(r, e) {
  const t = r.start + e;
  r.startPTS = t, r.setStart(t), r.endPTS = t + r.duration;
}
function g_(r, e) {
  const t = e.fragments;
  for (let i = 0, s = t.length; i < s; i++)
    Lp(t[i], r);
  e.fragmentHint && Lp(e.fragmentHint, r), e.alignedSliding = !0;
}
function n8(r, e) {
  r && (__(e, r), e.alignedSliding || oo(e, r), !e.alignedSliding && !e.skippedSegments && h_(r, e, !1));
}
function __(r, e) {
  if (!r8(e, r))
    return;
  const t = Math.min(e.endCC, r.endCC), i = ln(e.fragments, t), s = ln(r.fragments, t);
  if (!i || !s)
    return;
  Pe.log(`Aligning playlist at start of dicontinuity sequence ${t}`);
  const n = i.start - s.start;
  g_(n, r);
}
function oo(r, e) {
  if (!r.hasProgramDateTime || !e.hasProgramDateTime)
    return;
  const t = r.fragments, i = e.fragments;
  if (!t.length || !i.length)
    return;
  let s, n;
  const a = Math.min(e.endCC, r.endCC);
  e.startCC < a && r.startCC < a && (s = ln(i, a), n = ln(t, a)), (!s || !n) && (s = i[Math.floor(i.length / 2)], n = ln(t, s.cc) || t[Math.floor(t.length / 2)]);
  const o = s.programDateTime, c = n.programDateTime;
  if (!o || !c)
    return;
  const l = (c - o) / 1e3 - (n.start - s.start);
  g_(l, r);
}
function bt(r, e, t) {
  Ft(r, e, t), r.addEventListener(e, t);
}
function Ft(r, e, t) {
  r.removeEventListener(e, t);
}
const a8 = {
  toString: function(r) {
    let e = "";
    const t = r.length;
    for (let i = 0; i < t; i++)
      e += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
    return e;
  }
}, K = {
  STOPPED: "STOPPED",
  IDLE: "IDLE",
  KEY_LOADING: "KEY_LOADING",
  FRAG_LOADING: "FRAG_LOADING",
  FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  WAITING_TRACK: "WAITING_TRACK",
  PARSING: "PARSING",
  PARSED: "PARSED",
  ENDED: "ENDED",
  ERROR: "ERROR",
  WAITING_INIT_PTS: "WAITING_INIT_PTS",
  WAITING_LEVEL: "WAITING_LEVEL"
};
class Yd extends r_ {
  constructor(e, t, i, s, n) {
    super(s, e.logger), this.hls = void 0, this.fragPrevious = null, this.fragCurrent = null, this.fragmentTracker = void 0, this.transmuxer = null, this._state = K.STOPPED, this.playlistType = void 0, this.media = null, this.mediaBuffer = null, this.config = void 0, this.bitrateTest = !1, this.lastCurrentTime = 0, this.nextLoadPosition = 0, this.startPosition = 0, this.startTimeOffset = null, this.retryDate = 0, this.levels = null, this.fragmentLoader = void 0, this.keyLoader = void 0, this.levelLastLoaded = null, this.startFragRequested = !1, this.decrypter = void 0, this.initPTS = [], this.buffering = !0, this.loadingParts = !1, this.loopSn = void 0, this.onMediaSeeking = () => {
      const {
        config: a,
        fragCurrent: o,
        media: c,
        mediaBuffer: l,
        state: d
      } = this, h = c ? c.currentTime : 0, u = ce.bufferInfo(l || c, h, a.maxBufferHole), f = !u.len;
      if (this.log(`Media seeking to ${q(h) ? h.toFixed(3) : h}, state: ${d}, ${f ? "out of" : "in"} buffer`), this.state === K.ENDED)
        this.resetLoadingState();
      else if (o) {
        const p = a.maxFragLookUpTolerance, m = o.start - p, g = o.start + o.duration + p;
        if (f || g < u.start || m > u.end) {
          const x = h > g;
          (h < m || x) && (x && o.loader && (this.log(`Cancelling fragment load for seek (sn: ${o.sn})`), o.abortRequests(), this.resetLoadingState()), this.fragPrevious = null);
        }
      }
      if (c) {
        this.fragmentTracker.removeFragmentsInRange(h, 1 / 0, this.playlistType, !0);
        const p = this.lastCurrentTime;
        if (h > p && (this.lastCurrentTime = h), !this.loadingParts) {
          const m = Math.max(u.end, h), g = this.shouldLoadParts(this.getLevelDetails(), m);
          g && (this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${m.toFixed(2)}`), this.loadingParts = g);
        }
      }
      this.hls.hasEnoughToStart || (this.log(`Setting ${f ? "startPosition" : "nextLoadPosition"} to ${h} for seek without enough to start`), this.nextLoadPosition = h, f && (this.startPosition = h)), f && this.state === K.IDLE && this.tickImmediate();
    }, this.onMediaEnded = () => {
      this.log("setting startPosition to 0 because media ended"), this.startPosition = this.lastCurrentTime = 0;
    }, this.playlistType = n, this.hls = e, this.fragmentLoader = new kC(e.config), this.keyLoader = i, this.fragmentTracker = t, this.config = e.config, this.decrypter = new Zd(e.config);
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.off(T.ERROR, this.onError, this);
  }
  doTick() {
    this.onTickEnd();
  }
  onTickEnd() {
  }
  startLoad(e) {
  }
  stopLoad() {
    if (this.state === K.STOPPED)
      return;
    this.fragmentLoader.abort(), this.keyLoader.abort(this.playlistType);
    const e = this.fragCurrent;
    e != null && e.loader && (e.abortRequests(), this.fragmentTracker.removeFragment(e)), this.resetTransmuxer(), this.fragCurrent = null, this.fragPrevious = null, this.clearInterval(), this.clearNextTick(), this.state = K.STOPPED;
  }
  get startPositionValue() {
    const {
      nextLoadPosition: e,
      startPosition: t
    } = this;
    return t === -1 && e ? e : t;
  }
  get bufferingEnabled() {
    return this.buffering;
  }
  pauseBuffering() {
    this.buffering = !1;
  }
  resumeBuffering() {
    this.buffering = !0;
  }
  get inFlightFrag() {
    return {
      frag: this.fragCurrent,
      state: this.state
    };
  }
  _streamEnded(e, t) {
    if (t.live || !this.media)
      return !1;
    const i = e.end || 0, s = this.config.timelineOffset || 0;
    if (i <= s)
      return !1;
    const n = e.buffered;
    this.config.maxBufferHole && n && n.length > 1 && (e = ce.bufferedInfo(n, e.start, 0));
    const a = e.nextStart;
    if (a && a > s && a < t.edge || this.media.currentTime < e.start)
      return !1;
    const c = t.partList;
    if (c != null && c.length) {
      const d = c[c.length - 1];
      return ce.isBuffered(this.media, d.start + d.duration / 2);
    }
    const l = t.fragments[t.fragments.length - 1].type;
    return this.fragmentTracker.isEndListAppended(l);
  }
  getLevelDetails() {
    if (this.levels && this.levelLastLoaded !== null)
      return this.levelLastLoaded.details;
  }
  get timelineOffset() {
    const e = this.config.timelineOffset;
    if (e) {
      var t;
      return ((t = this.getLevelDetails()) == null ? void 0 : t.appliedTimelineOffset) || e;
    }
    return 0;
  }
  onMediaAttached(e, t) {
    const i = this.media = this.mediaBuffer = t.media;
    bt(i, "seeking", this.onMediaSeeking), bt(i, "ended", this.onMediaEnded);
    const s = this.config;
    this.levels && s.autoStartLoad && this.state === K.STOPPED && this.startLoad(s.startPosition);
  }
  onMediaDetaching(e, t) {
    const i = !!t.transferMedia, s = this.media;
    if (s !== null) {
      if (s.ended && (this.log("MSE detaching and video ended, reset startPosition"), this.startPosition = this.lastCurrentTime = 0), Ft(s, "seeking", this.onMediaSeeking), Ft(s, "ended", this.onMediaEnded), this.keyLoader && !i && this.keyLoader.detach(), this.media = this.mediaBuffer = null, this.loopSn = void 0, i) {
        this.resetLoadingState(), this.resetTransmuxer();
        return;
      }
      this.loadingParts = !1, this.fragmentTracker.removeAllFragments(), this.stopLoad();
    }
  }
  onManifestLoading() {
    this.initPTS = [], this.levels = this.levelLastLoaded = this.fragCurrent = null, this.lastCurrentTime = this.startPosition = 0, this.startFragRequested = !1;
  }
  onError(e, t) {
  }
  onManifestLoaded(e, t) {
    this.startTimeOffset = t.startTimeOffset;
  }
  onHandlerDestroying() {
    this.stopLoad(), this.transmuxer && (this.transmuxer.destroy(), this.transmuxer = null), super.onHandlerDestroying(), this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  }
  onHandlerDestroyed() {
    this.state = K.STOPPED, this.fragmentLoader && this.fragmentLoader.destroy(), this.keyLoader && this.keyLoader.destroy(), this.decrypter && this.decrypter.destroy(), this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null, super.onHandlerDestroyed();
  }
  loadFragment(e, t, i) {
    this.startFragRequested = !0, this._loadFragForPlayback(e, t, i);
  }
  _loadFragForPlayback(e, t, i) {
    const s = (n) => {
      const a = n.frag;
      if (this.fragContextChanged(a)) {
        this.warn(`${a.type} sn: ${a.sn}${n.part ? " part: " + n.part.index : ""} of ${this.fragInfo(a, !1, n.part)}) was dropped during download.`), this.fragmentTracker.removeFragment(a);
        return;
      }
      a.stats.chunkCount++, this._handleFragmentLoadProgress(n);
    };
    this._doFragLoad(e, t, i, s).then((n) => {
      if (!n)
        return;
      const a = this.state, o = n.frag;
      if (this.fragContextChanged(o)) {
        (a === K.FRAG_LOADING || !this.fragCurrent && a === K.PARSING) && (this.fragmentTracker.removeFragment(o), this.state = K.IDLE);
        return;
      }
      "payload" in n && (this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`), this.hls.trigger(T.FRAG_LOADED, n)), this._handleFragmentLoadComplete(n);
    }).catch((n) => {
      this.state === K.STOPPED || this.state === K.ERROR || (this.warn(`Frag error: ${(n == null ? void 0 : n.message) || n}`), this.resetFragmentLoading(e));
    });
  }
  clearTrackerIfNeeded(e) {
    var t;
    const {
      fragmentTracker: i
    } = this;
    if (i.getState(e) === nt.APPENDING) {
      const n = e.type, a = this.getFwdBufferInfo(this.mediaBuffer, n), o = Math.max(e.duration, a ? a.len : this.config.maxBufferLength), c = this.backtrackFragment;
      ((c ? e.sn - c.sn : 0) === 1 || this.reduceMaxBufferLength(o, e.duration)) && i.removeFragment(e);
    } else ((t = this.mediaBuffer) == null ? void 0 : t.buffered.length) === 0 ? i.removeAllFragments() : i.hasParts(e.type) && (i.detectPartialFragments({
      frag: e,
      part: null,
      stats: e.stats,
      id: e.type
    }), i.getState(e) === nt.PARTIAL && i.removeFragment(e));
  }
  checkLiveUpdate(e) {
    if (e.updated && !e.live) {
      const t = e.fragments[e.fragments.length - 1];
      this.fragmentTracker.detectPartialFragments({
        frag: t,
        part: null,
        stats: t.stats,
        id: t.type
      });
    }
    e.fragments[0] || (e.deltaUpdateFailed = !0);
  }
  waitForLive(e) {
    const t = e.details;
    return (t == null ? void 0 : t.live) && t.type !== "EVENT" && (this.levelLastLoaded !== e || t.expired);
  }
  flushMainBuffer(e, t, i = null) {
    if (!(e - t))
      return;
    const s = {
      startOffset: e,
      endOffset: t,
      type: i
    };
    this.hls.trigger(T.BUFFER_FLUSHING, s);
  }
  _loadInitSegment(e, t) {
    this._doFragLoad(e, t).then((i) => {
      const s = i == null ? void 0 : i.frag;
      if (!s || this.fragContextChanged(s) || !this.levels)
        throw new Error("init load aborted");
      return i;
    }).then((i) => {
      const {
        hls: s
      } = this, {
        frag: n,
        payload: a
      } = i, o = n.decryptdata;
      if (a && a.byteLength > 0 && o != null && o.key && o.iv && br(o.method)) {
        const c = self.performance.now();
        return this.decrypter.decrypt(new Uint8Array(a), o.key.buffer, o.iv.buffer, Kd(o.method)).catch((l) => {
          throw s.trigger(T.ERROR, {
            type: ie.MEDIA_ERROR,
            details: V.FRAG_DECRYPT_ERROR,
            fatal: !1,
            error: l,
            reason: l.message,
            frag: n
          }), l;
        }).then((l) => {
          const d = self.performance.now();
          return s.trigger(T.FRAG_DECRYPTED, {
            frag: n,
            payload: l,
            stats: {
              tstart: c,
              tdecrypt: d
            }
          }), i.payload = l, this.completeInitSegmentLoad(i);
        });
      }
      return this.completeInitSegmentLoad(i);
    }).catch((i) => {
      this.state === K.STOPPED || this.state === K.ERROR || (this.warn(i), this.resetFragmentLoading(e));
    });
  }
  completeInitSegmentLoad(e) {
    const {
      levels: t
    } = this;
    if (!t)
      throw new Error("init load aborted, missing levels");
    const i = e.frag.stats;
    this.state !== K.STOPPED && (this.state = K.IDLE), e.frag.data = new Uint8Array(e.payload), i.parsing.start = i.buffering.start = self.performance.now(), i.parsing.end = i.buffering.end = self.performance.now(), this.tick();
  }
  unhandledEncryptionError(e, t) {
    var i, s;
    const n = e.tracks;
    if (n && !t.encrypted && ((i = n.audio) != null && i.encrypted || (s = n.video) != null && s.encrypted) && (!this.config.emeEnabled || !this.keyLoader.emeController)) {
      const a = this.media, o = new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a ? "attached mediaKeys: " + a.mediaKeys : "detached"})`);
      return this.warn(o.message), !a || a.mediaKeys ? !1 : (this.hls.trigger(T.ERROR, {
        type: ie.KEY_SYSTEM_ERROR,
        details: V.KEY_SYSTEM_NO_KEYS,
        fatal: !1,
        error: o,
        frag: t
      }), this.resetTransmuxer(), !0);
    }
    return !1;
  }
  fragContextChanged(e) {
    const {
      fragCurrent: t
    } = this;
    return !e || !t || e.sn !== t.sn || e.level !== t.level;
  }
  fragBufferedComplete(e, t) {
    const i = this.mediaBuffer ? this.mediaBuffer : this.media;
    if (this.log(`Buffered ${e.type} sn: ${e.sn}${t ? " part: " + t.index : ""} of ${this.fragInfo(e, !1, t)} > buffer:${i ? a8.toString(ce.getBuffered(i)) : "(detached)"})`), et(e)) {
      var s;
      if (e.type !== te.SUBTITLE) {
        const a = e.elementaryStreams;
        if (!Object.keys(a).some((o) => !!a[o])) {
          this.state = K.IDLE;
          return;
        }
      }
      const n = (s = this.levels) == null ? void 0 : s[e.level];
      n != null && n.fragmentError && (this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`), n.fragmentError = 0);
    }
    this.state = K.IDLE;
  }
  _handleFragmentLoadComplete(e) {
    const {
      transmuxer: t
    } = this;
    if (!t)
      return;
    const {
      frag: i,
      part: s,
      partsLoaded: n
    } = e, a = !n || n.length === 0 || n.some((c) => !c), o = new $d(i.level, i.sn, i.stats.chunkCount + 1, 0, s ? s.index : -1, !a);
    t.flush(o);
  }
  _handleFragmentLoadProgress(e) {
  }
  _doFragLoad(e, t, i = null, s) {
    var n;
    this.fragCurrent = e;
    const a = t.details;
    if (!this.levels || !a)
      throw new Error(`frag load aborted, missing level${a ? "" : " detail"}s`);
    let o = null;
    if (e.encrypted && !((n = e.decryptdata) != null && n.key)) {
      if (this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`), this.state = K.KEY_LOADING, this.fragCurrent = e, o = this.keyLoader.load(e).then((u) => {
        if (!this.fragContextChanged(u.frag))
          return this.hls.trigger(T.KEY_LOADED, u), this.state === K.KEY_LOADING && (this.state = K.IDLE), u;
      }), this.hls.trigger(T.KEY_LOADING, {
        frag: e
      }), this.fragCurrent === null)
        return this.log("context changed in KEY_LOADING"), Promise.resolve(null);
    } else e.encrypted || (o = this.keyLoader.loadClear(e, a.encryptedFragments, this.startFragRequested), o && this.log("[eme] blocking frag load until media-keys acquired"));
    const c = this.fragPrevious;
    if (et(e) && (!c || e.sn !== c.sn)) {
      const u = this.shouldLoadParts(t.details, e.end);
      u !== this.loadingParts && (this.log(`LL-Part loading ${u ? "ON" : "OFF"} loading sn ${c == null ? void 0 : c.sn}->${e.sn}`), this.loadingParts = u);
    }
    if (i = Math.max(e.start, i || 0), this.loadingParts && et(e)) {
      const u = a.partList;
      if (u && s) {
        i > a.fragmentEnd && a.fragmentHint && (e = a.fragmentHint);
        const f = this.getNextPart(u, e, i);
        if (f > -1) {
          const p = u[f];
          e = this.fragCurrent = p.fragment, this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${u.length - 1}) of ${this.fragInfo(e, !1, p)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`), this.nextLoadPosition = p.start + p.duration, this.state = K.FRAG_LOADING;
          let m;
          return o ? m = o.then((g) => !g || this.fragContextChanged(g.frag) ? null : this.doFragPartsLoad(e, p, t, s)).catch((g) => this.handleFragLoadError(g)) : m = this.doFragPartsLoad(e, p, t, s).catch((g) => this.handleFragLoadError(g)), this.hls.trigger(T.FRAG_LOADING, {
            frag: e,
            part: p,
            targetBufferTime: i
          }), this.fragCurrent === null ? Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")) : m;
        } else if (!e.url || this.loadedEndOfParts(u, i))
          return Promise.resolve(null);
      }
    }
    if (et(e) && this.loadingParts) {
      var l;
      this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l = a.partList) == null ? void 0 : l.filter((u) => u.loaded).map((u) => `[${u.start}-${u.end}]`)}`), this.loadingParts = !1;
    } else if (!e.url)
      return Promise.resolve(null);
    this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e, !1)}) cc: ${e.cc} ${"[" + a.startSN + "-" + a.endSN + "]"}, target: ${parseFloat(i.toFixed(3))}`), q(e.sn) && !this.bitrateTest && (this.nextLoadPosition = e.start + e.duration), this.state = K.FRAG_LOADING;
    const d = this.config.progressive;
    let h;
    return d && o ? h = o.then((u) => !u || this.fragContextChanged(u.frag) ? null : this.fragmentLoader.load(e, s)).catch((u) => this.handleFragLoadError(u)) : h = Promise.all([this.fragmentLoader.load(e, d ? s : void 0), o]).then(([u]) => (!d && s && s(u), u)).catch((u) => this.handleFragLoadError(u)), this.hls.trigger(T.FRAG_LOADING, {
      frag: e,
      targetBufferTime: i
    }), this.fragCurrent === null ? Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")) : h;
  }
  doFragPartsLoad(e, t, i, s) {
    return new Promise((n, a) => {
      var o;
      const c = [], l = (o = i.details) == null ? void 0 : o.partList, d = (h) => {
        this.fragmentLoader.loadPart(e, h, s).then((u) => {
          c[h.index] = u;
          const f = u.part;
          this.hls.trigger(T.FRAG_LOADED, u);
          const p = Rp(i.details, e.sn, h.index + 1) || p_(l, e.sn, h.index + 1);
          if (p)
            d(p);
          else
            return n({
              frag: e,
              part: f,
              partsLoaded: c
            });
        }).catch(a);
      };
      d(t);
    });
  }
  handleFragLoadError(e) {
    if ("data" in e) {
      const t = e.data;
      t.frag && t.details === V.INTERNAL_ABORTED ? this.handleFragLoadAborted(t.frag, t.part) : t.frag && t.type === ie.KEY_SYSTEM_ERROR ? (t.frag.abortRequests(), this.resetFragmentLoading(t.frag)) : this.hls.trigger(T.ERROR, t);
    } else
      this.hls.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.INTERNAL_EXCEPTION,
        err: e,
        error: e,
        fatal: !0
      });
    return null;
  }
  _handleTransmuxerFlush(e) {
    const t = this.getCurrentContext(e);
    if (!t || this.state !== K.PARSING) {
      !this.fragCurrent && this.state !== K.STOPPED && this.state !== K.ERROR && (this.state = K.IDLE);
      return;
    }
    const {
      frag: i,
      part: s,
      level: n
    } = t, a = self.performance.now();
    i.stats.parsing.end = a, s && (s.stats.parsing.end = a);
    const o = this.getLevelDetails(), l = o && i.sn > o.endSN || this.shouldLoadParts(o, i.end);
    l !== this.loadingParts && (this.log(`LL-Part loading ${l ? "ON" : "OFF"} after parsing segment ending @${i.end.toFixed(2)}`), this.loadingParts = l), this.updateLevelTiming(i, s, n, e.partial);
  }
  shouldLoadParts(e, t) {
    if (this.config.lowLatencyMode) {
      if (!e)
        return this.loadingParts;
      if (e.partList) {
        var i;
        const n = e.partList[0];
        if (n.fragment.type === te.SUBTITLE)
          return !1;
        const a = n.end + (((i = e.fragmentHint) == null ? void 0 : i.duration) || 0);
        if (t >= a) {
          var s;
          if ((this.hls.hasEnoughToStart ? ((s = this.media) == null ? void 0 : s.currentTime) || this.lastCurrentTime : this.getLoadPosition()) > n.start - n.fragment.duration)
            return !0;
        }
      }
    }
    return !1;
  }
  getCurrentContext(e) {
    const {
      levels: t,
      fragCurrent: i
    } = this, {
      level: s,
      sn: n,
      part: a
    } = e;
    if (!(t != null && t[s]))
      return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`), null;
    const o = t[s], c = o.details, l = a > -1 ? Rp(c, n, a) : null, d = l ? l.fragment : f_(c, n, i);
    return d ? (i && i !== d && (d.stats = i.stats), {
      frag: d,
      part: l,
      level: o
    }) : null;
  }
  bufferFragmentData(e, t, i, s, n) {
    if (this.state !== K.PARSING)
      return;
    const {
      data1: a,
      data2: o
    } = e;
    let c = a;
    if (o && (c = Qt(a, o)), !c.length)
      return;
    const l = this.initPTS[t.cc], d = l ? -l.baseTime / l.timescale : void 0, h = {
      type: e.type,
      frag: t,
      part: i,
      chunkMeta: s,
      offset: d,
      parent: t.type,
      data: c
    };
    if (this.hls.trigger(T.BUFFER_APPENDING, h), e.dropped && e.independent && !i) {
      if (n)
        return;
      this.flushBufferGap(t);
    }
  }
  flushBufferGap(e) {
    const t = this.media;
    if (!t)
      return;
    if (!ce.isBuffered(t, t.currentTime)) {
      this.flushMainBuffer(0, e.start);
      return;
    }
    const i = t.currentTime, s = ce.bufferInfo(t, i, 0), n = e.duration, a = Math.min(this.config.maxFragLookUpTolerance * 2, n * 0.25), o = Math.max(Math.min(e.start - a, s.end - a), i + a);
    e.start - o > a && this.flushMainBuffer(o, e.start);
  }
  getFwdBufferInfo(e, t) {
    var i;
    const s = this.getLoadPosition();
    if (!q(s))
      return null;
    const a = this.lastCurrentTime > s || (i = this.media) != null && i.paused ? 0 : this.config.maxBufferHole;
    return this.getFwdBufferInfoAtPos(e, s, t, a);
  }
  getFwdBufferInfoAtPos(e, t, i, s) {
    const n = ce.bufferInfo(e, t, s);
    if (n.len === 0 && n.nextStart !== void 0) {
      const a = this.fragmentTracker.getBufferedFrag(t, i);
      if (a && (n.nextStart <= a.end || a.gap)) {
        const o = Math.max(Math.min(n.nextStart, a.end) - t, s);
        return ce.bufferInfo(e, t, o);
      }
    }
    return n;
  }
  getMaxBufferLength(e) {
    const {
      config: t
    } = this;
    let i;
    return e ? i = Math.max(8 * t.maxBufferSize / e, t.maxBufferLength) : i = t.maxBufferLength, Math.min(i, t.maxMaxBufferLength);
  }
  reduceMaxBufferLength(e, t) {
    const i = this.config, s = Math.max(Math.min(e - t, i.maxBufferLength), t), n = Math.max(e - t * 3, i.maxMaxBufferLength / 2, s);
    return n >= s ? (i.maxMaxBufferLength = n, this.warn(`Reduce max buffer length to ${n}s`), !0) : !1;
  }
  getAppendedFrag(e, t = te.MAIN) {
    const i = this.fragmentTracker ? this.fragmentTracker.getAppendedFrag(e, t) : null;
    return i && "fragment" in i ? i.fragment : i;
  }
  getNextFragment(e, t) {
    const i = t.fragments, s = i.length;
    if (!s)
      return null;
    const {
      config: n
    } = this, a = i[0].start, o = n.lowLatencyMode && !!t.partList;
    let c = null;
    if (t.live) {
      const h = n.initialLiveManifestSize;
      if (s < h)
        return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`), null;
      if (!t.PTSKnown && !this.startFragRequested && this.startPosition === -1 || e < a) {
        var l;
        o && !this.loadingParts && (this.log("LL-Part loading ON for initial live fragment"), this.loadingParts = !0), c = this.getInitialLiveFragment(t);
        const u = this.hls.startPosition, f = this.hls.liveSyncPosition, p = c ? (u !== -1 && u >= a ? u : f) || c.start : e;
        this.log(`Setting startPosition to ${p} to match start frag at live edge. mainStart: ${u} liveSyncPosition: ${f} frag.start: ${(l = c) == null ? void 0 : l.start}`), this.startPosition = this.nextLoadPosition = p;
      }
    } else e <= a && (c = i[0]);
    if (!c) {
      const h = this.loadingParts ? t.partEnd : t.fragmentEnd;
      c = this.getFragmentAtPosition(e, h, t);
    }
    let d = this.filterReplacedPrimary(c, t);
    if (!d && c) {
      const h = c.sn - t.startSN;
      d = this.filterReplacedPrimary(i[h + 1] || null, t);
    }
    return this.mapToInitFragWhenRequired(d);
  }
  isLoopLoading(e, t) {
    const i = this.fragmentTracker.getState(e);
    return (i === nt.OK || i === nt.PARTIAL && !!e.gap) && this.nextLoadPosition > t;
  }
  getNextFragmentLoopLoading(e, t, i, s, n) {
    let a = null;
    if (e.gap && (a = this.getNextFragment(this.nextLoadPosition, t), a && !a.gap && i.nextStart)) {
      const o = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, i.nextStart, s, 0);
      if (o !== null && i.len + o.len >= n) {
        const c = a.sn;
        return this.loopSn !== c && (this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${c}`), this.loopSn = c), null;
      }
    }
    return this.loopSn = void 0, a;
  }
  get primaryPrefetch() {
    if (Dp(this.config)) {
      var e;
      if ((e = this.hls.interstitialsManager) == null || (e = e.playingItem) == null ? void 0 : e.event)
        return !0;
    }
    return !1;
  }
  filterReplacedPrimary(e, t) {
    if (!e)
      return e;
    if (Dp(this.config) && e.type !== te.SUBTITLE) {
      const i = this.hls.interstitialsManager, s = i == null ? void 0 : i.bufferingItem;
      if (s) {
        const a = s.event;
        if (a) {
          if (a.appendInPlace || Math.abs(e.start - s.start) > 1 || s.start === 0)
            return null;
        } else if (e.end <= s.start && (t == null ? void 0 : t.live) === !1 || e.start > s.end && s.nextEvent && (s.nextEvent.appendInPlace || e.start - s.end > 1))
          return null;
      }
      const n = i == null ? void 0 : i.playerQueue;
      if (n)
        for (let a = n.length; a--; ) {
          const o = n[a].interstitial;
          if (o.appendInPlace && e.start >= o.startTime && e.end <= o.resumeTime)
            return null;
        }
    }
    return e;
  }
  mapToInitFragWhenRequired(e) {
    return e != null && e.initSegment && !e.initSegment.data && !this.bitrateTest ? e.initSegment : e;
  }
  getNextPart(e, t, i) {
    let s = -1, n = !1, a = !0;
    for (let o = 0, c = e.length; o < c; o++) {
      const l = e[o];
      if (a = a && !l.independent, s > -1 && i < l.start)
        break;
      const d = l.loaded;
      d ? s = -1 : (n || (l.independent || a) && l.fragment === t) && (l.fragment !== t && this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`), s = o), n = d;
    }
    return s;
  }
  loadedEndOfParts(e, t) {
    let i;
    for (let s = e.length; s--; ) {
      if (i = e[s], !i.loaded)
        return !1;
      if (t > i.start)
        return !0;
    }
    return !1;
  }
  /*
   This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
   "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
   start and end times for each fragment in the playlist (after which this method will not need to be called).
  */
  getInitialLiveFragment(e) {
    const t = e.fragments, i = this.fragPrevious;
    let s = null;
    if (i) {
      if (e.hasProgramDateTime && (this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`), s = vC(t, i.endProgramDateTime, this.config.maxFragLookUpTolerance)), !s) {
        const n = i.sn + 1;
        if (n >= e.startSN && n <= e.endSN) {
          const a = t[n - e.startSN];
          i.cc === a.cc && (s = a, this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`));
        }
        s || (s = s_(e, i.cc, i.end), s && this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`));
      }
    } else {
      const n = this.hls.liveSyncPosition;
      n !== null && (s = this.getFragmentAtPosition(n, this.bitrateTest ? e.fragmentEnd : e.edge, e));
    }
    return s;
  }
  /*
  This method finds the best matching fragment given the provided position.
   */
  getFragmentAtPosition(e, t, i) {
    const {
      config: s
    } = this;
    let {
      fragPrevious: n
    } = this, {
      fragments: a,
      endSN: o
    } = i;
    const {
      fragmentHint: c
    } = i, {
      maxFragLookUpTolerance: l
    } = s, d = i.partList, h = !!(this.loadingParts && d != null && d.length && c);
    h && !this.bitrateTest && d[d.length - 1].fragment.sn === c.sn && (a = a.concat(c), o = c.sn);
    let u;
    if (e < t) {
      var f;
      const m = e < this.lastCurrentTime || e > t - l || (f = this.media) != null && f.paused || !this.startFragRequested ? 0 : l;
      u = Hs(n, a, e, m);
    } else
      u = a[a.length - 1];
    if (u) {
      const p = u.sn - i.startSN, m = this.fragmentTracker.getState(u);
      if ((m === nt.OK || m === nt.PARTIAL && u.gap) && (n = u), n && u.sn === n.sn && (!h || d[0].fragment.sn > u.sn || !i.live) && u.level === n.level) {
        const x = a[p + 1];
        u.sn < o && this.fragmentTracker.getState(x) !== nt.OK ? u = x : u = null;
      }
    }
    return u;
  }
  alignPlaylists(e, t, i) {
    const s = e.fragments.length;
    if (!s)
      return this.warn("No fragments in live playlist"), 0;
    const n = e.fragmentStart, a = !t, o = e.alignedSliding && q(n);
    if (a || !o && !n) {
      n8(i, e);
      const c = e.fragmentStart;
      return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t ? t.startSN : "na"}->${e.startSN} fragments: ${s}`), c;
    }
    return n;
  }
  waitForCdnTuneIn(e) {
    return e.live && e.canBlockReload && e.partTarget && e.tuneInGoal > Math.max(e.partHoldBack, e.partTarget * 3);
  }
  setStartPosition(e, t) {
    let i = this.startPosition;
    i < t && (i = -1);
    const s = this.timelineOffset;
    if (i === -1) {
      const n = this.startTimeOffset !== null, a = n ? this.startTimeOffset : e.startTimeOffset;
      a !== null && q(a) ? (i = t + a, a < 0 && (i += e.edge), i = Math.min(Math.max(t, i), t + e.totalduration), this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n ? "multivariant" : "media"} playlist`), this.startPosition = i) : e.live ? (i = this.hls.liveSyncPosition || t, this.log(`Setting startPosition to -1 to start at live edge ${i}`), this.startPosition = -1) : (this.log("setting startPosition to 0 by default"), this.startPosition = i = 0), this.lastCurrentTime = i + s;
    }
    this.nextLoadPosition = i + s;
  }
  getLoadPosition() {
    var e;
    const {
      media: t
    } = this;
    let i = 0;
    return (e = this.hls) != null && e.hasEnoughToStart && t ? i = t.currentTime : this.nextLoadPosition >= 0 && (i = this.nextLoadPosition), i;
  }
  handleFragLoadAborted(e, t) {
    this.transmuxer && e.type === this.playlistType && et(e) && e.stats.aborted && (this.log(`Fragment ${e.sn}${t ? " part " + t.index : ""} of ${this.playlistLabel()} ${e.level} was aborted`), this.resetFragmentLoading(e));
  }
  resetFragmentLoading(e) {
    (!this.fragCurrent || !this.fragContextChanged(e) && this.state !== K.FRAG_LOADING_WAITING_RETRY) && (this.state = K.IDLE);
  }
  onFragmentOrKeyLoadError(e, t) {
    var i;
    if (t.chunkMeta && !t.frag) {
      const x = this.getCurrentContext(t.chunkMeta);
      x && (t.frag = x.frag);
    }
    const s = t.frag;
    if (!s || s.type !== e || !this.levels)
      return;
    if (this.fragContextChanged(s)) {
      var n;
      this.warn(`Frag load error must match current frag to retry ${s.url} > ${(n = this.fragCurrent) == null ? void 0 : n.url}`);
      return;
    }
    const a = t.details === V.FRAG_GAP;
    a && this.fragmentTracker.fragBuffered(s, !0);
    const o = t.errorAction;
    if (!o) {
      this.state = K.ERROR;
      return;
    }
    const {
      action: c,
      flags: l,
      retryCount: d = 0,
      retryConfig: h
    } = o, u = !!h, f = u && c === ft.RetryRequest, p = u && !o.resolved && l === Vt.MoveAllAlternatesMatchingHost, m = (i = this.hls.latestLevelDetails) == null ? void 0 : i.live;
    if (!f && p && et(s) && !s.endList && m)
      this.resetFragmentErrors(e), this.treatAsGap(s), o.resolved = !0;
    else if ((f || p) && d < h.maxNumRetry) {
      var g;
      const x = kc((g = t.response) == null ? void 0 : g.code), _ = Hd(h, d);
      if (this.resetStartWhenNotLoaded(), this.retryDate = self.performance.now() + _, this.state = K.FRAG_LOADING_WAITING_RETRY, o.resolved = !0, x) {
        this.log("Waiting for connection (offline)"), this.retryDate = 1 / 0, t.reason = "offline";
        return;
      }
      this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d + 1}/${h.maxNumRetry} in ${_}ms`);
    } else if (h)
      if (this.resetFragmentErrors(e), d < h.maxNumRetry)
        !a && c !== ft.RemoveAlternatePermanently && (o.resolved = !0);
      else {
        this.warn(`${t.details} reached or exceeded max retry (${d})`);
        return;
      }
    else c === ft.SendAlternateToPenaltyBox ? this.state = K.WAITING_LEVEL : this.state = K.ERROR;
    this.tickImmediate();
  }
  checkRetryDate() {
    const e = self.performance.now(), t = this.retryDate, i = t === 1 / 0;
    (!t || e >= t || i && !kc(0)) && (i && this.log("Connection restored (online)"), this.resetStartWhenNotLoaded(), this.state = K.IDLE);
  }
  reduceLengthAndFlushBuffer(e) {
    if (this.state === K.PARSING || this.state === K.PARSED) {
      const t = e.frag, i = e.parent, s = this.getFwdBufferInfo(this.mediaBuffer, i), n = s && s.len > 0.5;
      n && this.reduceMaxBufferLength(s.len, (t == null ? void 0 : t.duration) || 10);
      const a = !n;
      return a && this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`), t && (this.fragmentTracker.removeFragment(t), this.nextLoadPosition = t.start), this.resetLoadingState(), a;
    }
    return !1;
  }
  resetFragmentErrors(e) {
    e === te.AUDIO && (this.fragCurrent = null), this.hls.hasEnoughToStart || (this.startFragRequested = !1), this.state !== K.STOPPED && (this.state = K.IDLE);
  }
  afterBufferFlushed(e, t, i) {
    if (!e)
      return;
    const s = ce.getBuffered(e);
    this.fragmentTracker.detectEvictedFragments(t, s, i), this.state === K.ENDED && this.resetLoadingState();
  }
  resetLoadingState() {
    this.log("Reset loading state"), this.fragCurrent = null, this.fragPrevious = null, this.state !== K.STOPPED && (this.state = K.IDLE);
  }
  resetStartWhenNotLoaded() {
    if (!this.hls.hasEnoughToStart) {
      this.startFragRequested = !1;
      const e = this.levelLastLoaded, t = e ? e.details : null;
      t != null && t.live ? (this.log("resetting startPosition for live start"), this.startPosition = -1, this.setStartPosition(t, t.fragmentStart), this.resetLoadingState()) : this.nextLoadPosition = this.startPosition;
    }
  }
  resetWhenMissingContext(e) {
    this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level === -1 ? "<removed>" : e.level}. This chunk will not be buffered.`), this.removeUnbufferedFrags(), this.resetStartWhenNotLoaded(), this.resetLoadingState();
  }
  removeUnbufferedFrags(e = 0) {
    this.fragmentTracker.removeFragmentsInRange(e, 1 / 0, this.playlistType, !1, !0);
  }
  updateLevelTiming(e, t, i, s) {
    const n = i.details;
    if (!n) {
      this.warn("level.details undefined");
      return;
    }
    if (!Object.keys(e.elementaryStreams).reduce((c, l) => {
      const d = e.elementaryStreams[l];
      if (d) {
        const h = d.endPTS - d.startPTS;
        if (h <= 0)
          return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${h})`), c || !1;
        const u = s ? 0 : d_(n, e, d.startPTS, d.endPTS, d.startDTS, d.endDTS, this);
        return this.hls.trigger(T.LEVEL_PTS_UPDATED, {
          details: n,
          level: i,
          drift: u,
          type: l,
          frag: e,
          start: d.startPTS,
          end: d.endPTS
        }), !0;
      }
      return c;
    }, !1)) {
      var o;
      if (i.fragmentError === 0 && this.treatAsGap(e, i), ((o = this.transmuxer) == null ? void 0 : o.error) === null) {
        const c = new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);
        if (this.warn(c.message), this.hls.trigger(T.ERROR, {
          type: ie.MEDIA_ERROR,
          details: V.FRAG_PARSING_ERROR,
          fatal: !1,
          error: c,
          frag: e,
          reason: `Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`
        }), !this.hls)
          return;
        this.resetTransmuxer();
      }
    }
    this.state = K.PARSED, this.log(`Parsed ${e.type} sn: ${e.sn}${t ? " part: " + t.index : ""} of ${this.fragInfo(e, !1, t)})`), this.hls.trigger(T.FRAG_PARSED, {
      frag: e,
      part: t
    });
  }
  playlistLabel() {
    return this.playlistType === te.MAIN ? "level" : "track";
  }
  fragInfo(e, t = !0, i) {
    var s, n;
    return `${this.playlistLabel()} ${e.level} (${i ? "part" : "frag"}:[${((s = t && !i ? e.startPTS : (i || e).start) != null ? s : NaN).toFixed(3)}-${((n = t && !i ? e.endPTS : (i || e).end) != null ? n : NaN).toFixed(3)}]${i && e.type === "main" ? "INDEPENDENT=" + (i.independent ? "YES" : "NO") : ""}`;
  }
  treatAsGap(e, t) {
    t && t.fragmentError++, e.gap = !0, this.fragmentTracker.removeFragment(e), this.fragmentTracker.fragBuffered(e, !0);
  }
  resetTransmuxer() {
    var e;
    (e = this.transmuxer) == null || e.reset();
  }
  recoverWorkerError(e) {
    e.event === "demuxerWorker" && (this.fragmentTracker.removeAllFragments(), this.transmuxer && (this.transmuxer.destroy(), this.transmuxer = null), this.resetStartWhenNotLoaded(), this.resetLoadingState());
  }
  set state(e) {
    const t = this._state;
    t !== e && (this._state = e, this.log(`${t}->${e}`));
  }
  get state() {
    return this._state;
  }
}
function Dp(r) {
  return !!r.interstitialsController && r.enableInterstitialPlayback !== !1;
}
class y_ {
  constructor() {
    this.chunks = [], this.dataLength = 0;
  }
  push(e) {
    this.chunks.push(e), this.dataLength += e.length;
  }
  flush() {
    const {
      chunks: e,
      dataLength: t
    } = this;
    let i;
    if (e.length)
      e.length === 1 ? i = e[0] : i = o8(e, t);
    else return new Uint8Array(0);
    return this.reset(), i;
  }
  reset() {
    this.chunks.length = 0, this.dataLength = 0;
  }
}
function o8(r, e) {
  const t = new Uint8Array(e);
  let i = 0;
  for (let s = 0; s < r.length; s++) {
    const n = r[s];
    t.set(n, i), i += n.length;
  }
  return t;
}
var T0 = { exports: {} }, Pp;
function l8() {
  return Pp || (Pp = 1, function(r) {
    var e = Object.prototype.hasOwnProperty, t = "~";
    function i() {
    }
    Object.create && (i.prototype = /* @__PURE__ */ Object.create(null), new i().__proto__ || (t = !1));
    function s(c, l, d) {
      this.fn = c, this.context = l, this.once = d || !1;
    }
    function n(c, l, d, h, u) {
      if (typeof d != "function")
        throw new TypeError("The listener must be a function");
      var f = new s(d, h || c, u), p = t ? t + l : l;
      return c._events[p] ? c._events[p].fn ? c._events[p] = [c._events[p], f] : c._events[p].push(f) : (c._events[p] = f, c._eventsCount++), c;
    }
    function a(c, l) {
      --c._eventsCount === 0 ? c._events = new i() : delete c._events[l];
    }
    function o() {
      this._events = new i(), this._eventsCount = 0;
    }
    o.prototype.eventNames = function() {
      var l = [], d, h;
      if (this._eventsCount === 0) return l;
      for (h in d = this._events)
        e.call(d, h) && l.push(t ? h.slice(1) : h);
      return Object.getOwnPropertySymbols ? l.concat(Object.getOwnPropertySymbols(d)) : l;
    }, o.prototype.listeners = function(l) {
      var d = t ? t + l : l, h = this._events[d];
      if (!h) return [];
      if (h.fn) return [h.fn];
      for (var u = 0, f = h.length, p = new Array(f); u < f; u++)
        p[u] = h[u].fn;
      return p;
    }, o.prototype.listenerCount = function(l) {
      var d = t ? t + l : l, h = this._events[d];
      return h ? h.fn ? 1 : h.length : 0;
    }, o.prototype.emit = function(l, d, h, u, f, p) {
      var m = t ? t + l : l;
      if (!this._events[m]) return !1;
      var g = this._events[m], x = arguments.length, _, v;
      if (g.fn) {
        switch (g.once && this.removeListener(l, g.fn, void 0, !0), x) {
          case 1:
            return g.fn.call(g.context), !0;
          case 2:
            return g.fn.call(g.context, d), !0;
          case 3:
            return g.fn.call(g.context, d, h), !0;
          case 4:
            return g.fn.call(g.context, d, h, u), !0;
          case 5:
            return g.fn.call(g.context, d, h, u, f), !0;
          case 6:
            return g.fn.call(g.context, d, h, u, f, p), !0;
        }
        for (v = 1, _ = new Array(x - 1); v < x; v++)
          _[v - 1] = arguments[v];
        g.fn.apply(g.context, _);
      } else {
        var E = g.length, b;
        for (v = 0; v < E; v++)
          switch (g[v].once && this.removeListener(l, g[v].fn, void 0, !0), x) {
            case 1:
              g[v].fn.call(g[v].context);
              break;
            case 2:
              g[v].fn.call(g[v].context, d);
              break;
            case 3:
              g[v].fn.call(g[v].context, d, h);
              break;
            case 4:
              g[v].fn.call(g[v].context, d, h, u);
              break;
            default:
              if (!_) for (b = 1, _ = new Array(x - 1); b < x; b++)
                _[b - 1] = arguments[b];
              g[v].fn.apply(g[v].context, _);
          }
      }
      return !0;
    }, o.prototype.on = function(l, d, h) {
      return n(this, l, d, h, !1);
    }, o.prototype.once = function(l, d, h) {
      return n(this, l, d, h, !0);
    }, o.prototype.removeListener = function(l, d, h, u) {
      var f = t ? t + l : l;
      if (!this._events[f]) return this;
      if (!d)
        return a(this, f), this;
      var p = this._events[f];
      if (p.fn)
        p.fn === d && (!u || p.once) && (!h || p.context === h) && a(this, f);
      else {
        for (var m = 0, g = [], x = p.length; m < x; m++)
          (p[m].fn !== d || u && !p[m].once || h && p[m].context !== h) && g.push(p[m]);
        g.length ? this._events[f] = g.length === 1 ? g[0] : g : a(this, f);
      }
      return this;
    }, o.prototype.removeAllListeners = function(l) {
      var d;
      return l ? (d = t ? t + l : l, this._events[d] && a(this, d)) : (this._events = new i(), this._eventsCount = 0), this;
    }, o.prototype.off = o.prototype.removeListener, o.prototype.addListener = o.prototype.on, o.prefixed = t, o.EventEmitter = o, r.exports = o;
  }(T0)), T0.exports;
}
var c8 = l8(), zd = /* @__PURE__ */ B4(c8);
const Sn = "1.6.11", wr = {};
function d8() {
  return typeof __HLS_WORKER_BUNDLE__ == "function";
}
function h8() {
  const r = wr[Sn];
  if (r)
    return r.clientCount++, r;
  const e = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
    type: "text/javascript"
  }), t = self.URL.createObjectURL(e), s = {
    worker: new self.Worker(t),
    objectURL: t,
    clientCount: 1
  };
  return wr[Sn] = s, s;
}
function u8(r) {
  const e = wr[r];
  if (e)
    return e.clientCount++, e;
  const t = new self.URL(r, self.location.href).href, s = {
    worker: new self.Worker(t),
    scriptURL: t,
    clientCount: 1
  };
  return wr[r] = s, s;
}
function f8(r) {
  const e = wr[r || Sn];
  if (e && e.clientCount-- === 1) {
    const {
      worker: i,
      objectURL: s
    } = e;
    delete wr[r || Sn], s && self.URL.revokeObjectURL(s), i.terminate();
  }
}
function x_(r, e) {
  return e + 10 <= r.length && r[e] === 51 && r[e + 1] === 68 && r[e + 2] === 73 && r[e + 3] < 255 && r[e + 4] < 255 && r[e + 6] < 128 && r[e + 7] < 128 && r[e + 8] < 128 && r[e + 9] < 128;
}
function jd(r, e) {
  return e + 10 <= r.length && r[e] === 73 && r[e + 1] === 68 && r[e + 2] === 51 && r[e + 3] < 255 && r[e + 4] < 255 && r[e + 6] < 128 && r[e + 7] < 128 && r[e + 8] < 128 && r[e + 9] < 128;
}
function Lo(r, e) {
  let t = 0;
  return t = (r[e] & 127) << 21, t |= (r[e + 1] & 127) << 14, t |= (r[e + 2] & 127) << 7, t |= r[e + 3] & 127, t;
}
function Tn(r, e) {
  const t = e;
  let i = 0;
  for (; jd(r, e); ) {
    i += 10;
    const s = Lo(r, e + 6);
    i += s, x_(r, e + 10) && (i += 10), e += i;
  }
  if (i > 0)
    return r.subarray(t, t + i);
}
function p8(r, e, t, i) {
  const s = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], n = e[t + 2], a = n >> 2 & 15;
  if (a > 12) {
    const f = new Error(`invalid ADTS sampling index:${a}`);
    r.emit(T.ERROR, T.ERROR, {
      type: ie.MEDIA_ERROR,
      details: V.FRAG_PARSING_ERROR,
      fatal: !0,
      error: f,
      reason: f.message
    });
    return;
  }
  const o = (n >> 6 & 3) + 1, c = e[t + 3] >> 6 & 3 | (n & 1) << 2, l = "mp4a.40." + o, d = s[a];
  let h = a;
  (o === 5 || o === 29) && (h -= 3);
  const u = [o << 3 | (h & 14) >> 1, (h & 1) << 7 | c << 3];
  return Pe.log(`manifest codec:${i}, parsed codec:${l}, channels:${c}, rate:${d} (ADTS object type:${o} sampling index:${a})`), {
    config: u,
    samplerate: d,
    channelCount: c,
    codec: l,
    parsedCodec: l,
    manifestCodec: i
  };
}
function v_(r, e) {
  return r[e] === 255 && (r[e + 1] & 246) === 240;
}
function E_(r, e) {
  return r[e + 1] & 1 ? 7 : 9;
}
function Qd(r, e) {
  return (r[e + 3] & 3) << 11 | r[e + 4] << 3 | (r[e + 5] & 224) >>> 5;
}
function m8(r, e) {
  return e + 5 < r.length;
}
function lo(r, e) {
  return e + 1 < r.length && v_(r, e);
}
function g8(r, e) {
  return m8(r, e) && v_(r, e) && Qd(r, e) <= r.length - e;
}
function _8(r, e) {
  if (lo(r, e)) {
    const t = E_(r, e);
    if (e + t >= r.length)
      return !1;
    const i = Qd(r, e);
    if (i <= t)
      return !1;
    const s = e + i;
    return s === r.length || lo(r, s);
  }
  return !1;
}
function S_(r, e, t, i, s) {
  if (!r.samplerate) {
    const n = p8(e, t, i, s);
    if (!n)
      return;
    Me(r, n);
  }
}
function T_(r) {
  return 1024 * 9e4 / r;
}
function y8(r, e) {
  const t = E_(r, e);
  if (e + t <= r.length) {
    const i = Qd(r, e) - t;
    if (i > 0)
      return {
        headerLength: t,
        frameLength: i
      };
  }
}
function b_(r, e, t, i, s) {
  const n = T_(r.samplerate), a = i + s * n, o = y8(e, t);
  let c;
  if (o) {
    const {
      frameLength: h,
      headerLength: u
    } = o, f = u + h, p = Math.max(0, t + f - e.length);
    p ? (c = new Uint8Array(f - u), c.set(e.subarray(t + u, e.length), 0)) : c = e.subarray(t + u, t + f);
    const m = {
      unit: c,
      pts: a
    };
    return p || r.samples.push(m), {
      sample: m,
      length: f,
      missing: p
    };
  }
  const l = e.length - t;
  return c = new Uint8Array(l), c.set(e.subarray(t, e.length), 0), {
    sample: {
      unit: c,
      pts: a
    },
    length: l,
    missing: -1
  };
}
function x8(r, e) {
  return jd(r, e) && Lo(r, e + 6) + 10 <= r.length - e;
}
function v8(r) {
  return r instanceof ArrayBuffer ? r : r.byteOffset == 0 && r.byteLength == r.buffer.byteLength ? r.buffer : new Uint8Array(r).buffer;
}
function b0(r, e = 0, t = 1 / 0) {
  return E8(r, e, t, Uint8Array);
}
function E8(r, e, t, i) {
  const s = S8(r);
  let n = 1;
  "BYTES_PER_ELEMENT" in i && (n = i.BYTES_PER_ELEMENT);
  const a = T8(r) ? r.byteOffset : 0, o = (a + r.byteLength) / n, c = (a + e) / n, l = Math.floor(Math.max(0, Math.min(c, o))), d = Math.floor(Math.min(l + Math.max(t, 0), o));
  return new i(s, l, d - l);
}
function S8(r) {
  return r instanceof ArrayBuffer ? r : r.buffer;
}
function T8(r) {
  return r && r.buffer instanceof ArrayBuffer && r.byteLength !== void 0 && r.byteOffset !== void 0;
}
function b8(r) {
  const e = {
    key: r.type,
    description: "",
    data: "",
    mimeType: null,
    pictureType: null
  }, t = 3;
  if (r.size < 2)
    return;
  if (r.data[0] !== t) {
    console.log("Ignore frame with unrecognized character encoding");
    return;
  }
  const i = r.data.subarray(1).indexOf(0);
  if (i === -1)
    return;
  const s = $t(b0(r.data, 1, i)), n = r.data[2 + i], a = r.data.subarray(3 + i).indexOf(0);
  if (a === -1)
    return;
  const o = $t(b0(r.data, 3 + i, a));
  let c;
  return s === "-->" ? c = $t(b0(r.data, 4 + i + a)) : c = v8(r.data.subarray(4 + i + a)), e.mimeType = s, e.pictureType = n, e.description = o, e.data = c, e;
}
function A8(r) {
  if (r.size < 2)
    return;
  const e = $t(r.data, !0), t = new Uint8Array(r.data.subarray(e.length + 1));
  return {
    key: r.type,
    info: e,
    data: t.buffer
  };
}
function C8(r) {
  if (r.size < 2)
    return;
  if (r.type === "TXXX") {
    let t = 1;
    const i = $t(r.data.subarray(t), !0);
    t += i.length + 1;
    const s = $t(r.data.subarray(t));
    return {
      key: r.type,
      info: i,
      data: s
    };
  }
  const e = $t(r.data.subarray(1));
  return {
    key: r.type,
    info: "",
    data: e
  };
}
function R8(r) {
  if (r.type === "WXXX") {
    if (r.size < 2)
      return;
    let t = 1;
    const i = $t(r.data.subarray(t), !0);
    t += i.length + 1;
    const s = $t(r.data.subarray(t));
    return {
      key: r.type,
      info: i,
      data: s
    };
  }
  const e = $t(r.data);
  return {
    key: r.type,
    info: "",
    data: e
  };
}
function I8(r) {
  return r.type === "PRIV" ? A8(r) : r.type[0] === "W" ? R8(r) : r.type === "APIC" ? b8(r) : C8(r);
}
function L8(r) {
  const e = String.fromCharCode(r[0], r[1], r[2], r[3]), t = Lo(r, 4), i = 10;
  return {
    type: e,
    size: t,
    data: r.subarray(i, i + t)
  };
}
const ea = 10, D8 = 10;
function A_(r) {
  let e = 0;
  const t = [];
  for (; jd(r, e); ) {
    const i = Lo(r, e + 6);
    r[e + 5] >> 6 & 1 && (e += ea), e += ea;
    const s = e + i;
    for (; e + D8 < s; ) {
      const n = L8(r.subarray(e)), a = I8(n);
      a && t.push(a), e += n.size + ea;
    }
    x_(r, e) && (e += ea);
  }
  return t;
}
function C_(r) {
  return r && r.key === "PRIV" && r.info === "com.apple.streaming.transportStreamTimestamp";
}
function P8(r) {
  if (r.data.byteLength === 8) {
    const e = new Uint8Array(r.data), t = e[3] & 1;
    let i = (e[4] << 23) + (e[5] << 15) + (e[6] << 7) + e[7];
    return i /= 45, t && (i += 4772185884e-2), Math.round(i);
  }
}
function Jd(r) {
  const e = A_(r);
  for (let t = 0; t < e.length; t++) {
    const i = e[t];
    if (C_(i))
      return P8(i);
  }
}
let Ht = /* @__PURE__ */ function(r) {
  return r.audioId3 = "org.id3", r.dateRange = "com.apple.quicktime.HLS", r.emsg = "https://aomedia.org/emsg/ID3", r.misbklv = "urn:misb:KLV:bin:1910.1", r;
}({});
function Ci(r = "", e = 9e4) {
  return {
    type: r,
    id: -1,
    pid: -1,
    inputTimeScale: e,
    sequenceNumber: -1,
    samples: [],
    dropped: 0
  };
}
class qd {
  constructor() {
    this._audioTrack = void 0, this._id3Track = void 0, this.frameIndex = 0, this.cachedData = null, this.basePTS = null, this.initPTS = null, this.lastPTS = null;
  }
  resetInitSegment(e, t, i, s) {
    this._id3Track = {
      type: "id3",
      id: 3,
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0
    };
  }
  resetTimeStamp(e) {
    this.initPTS = e, this.resetContiguity();
  }
  resetContiguity() {
    this.basePTS = null, this.lastPTS = null, this.frameIndex = 0;
  }
  canParse(e, t) {
    return !1;
  }
  appendFrame(e, t, i) {
  }
  // feed incoming data to the front of the parsing pipeline
  demux(e, t) {
    this.cachedData && (e = Qt(this.cachedData, e), this.cachedData = null);
    let i = Tn(e, 0), s = i ? i.length : 0, n;
    const a = this._audioTrack, o = this._id3Track, c = i ? Jd(i) : void 0, l = e.length;
    for ((this.basePTS === null || this.frameIndex === 0 && q(c)) && (this.basePTS = k8(c, t, this.initPTS), this.lastPTS = this.basePTS), this.lastPTS === null && (this.lastPTS = this.basePTS), i && i.length > 0 && o.samples.push({
      pts: this.lastPTS,
      dts: this.lastPTS,
      data: i,
      type: Ht.audioId3,
      duration: Number.POSITIVE_INFINITY
    }); s < l; ) {
      if (this.canParse(e, s)) {
        const d = this.appendFrame(a, e, s);
        d ? (this.frameIndex++, this.lastPTS = d.sample.pts, s += d.length, n = s) : s = l;
      } else x8(e, s) ? (i = Tn(e, s), o.samples.push({
        pts: this.lastPTS,
        dts: this.lastPTS,
        data: i,
        type: Ht.audioId3,
        duration: Number.POSITIVE_INFINITY
      }), s += i.length, n = s) : s++;
      if (s === l && n !== l) {
        const d = e.slice(n);
        this.cachedData ? this.cachedData = Qt(this.cachedData, d) : this.cachedData = d;
      }
    }
    return {
      audioTrack: a,
      videoTrack: Ci(),
      id3Track: o,
      textTrack: Ci()
    };
  }
  demuxSampleAes(e, t, i) {
    return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  }
  flush(e) {
    const t = this.cachedData;
    return t && (this.cachedData = null, this.demux(t, 0)), {
      audioTrack: this._audioTrack,
      videoTrack: Ci(),
      id3Track: this._id3Track,
      textTrack: Ci()
    };
  }
  destroy() {
    this.cachedData = null, this._audioTrack = this._id3Track = void 0;
  }
}
const k8 = (r, e, t) => {
  if (q(r))
    return r * 90;
  const i = t ? t.baseTime * 9e4 / t.timescale : 0;
  return e * 9e4 + i;
};
let ta = null;
const w8 = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], M8 = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3], B8 = [
  // MPEG 2.5
  [
    0,
    // Reserved
    72,
    // Layer3
    144,
    // Layer2
    12
    // Layer1
  ],
  // Reserved
  [
    0,
    // Reserved
    0,
    // Layer3
    0,
    // Layer2
    0
    // Layer1
  ],
  // MPEG 2
  [
    0,
    // Reserved
    72,
    // Layer3
    144,
    // Layer2
    12
    // Layer1
  ],
  // MPEG 1
  [
    0,
    // Reserved
    144,
    // Layer3
    144,
    // Layer2
    12
    // Layer1
  ]
], F8 = [
  0,
  // Reserved
  1,
  // Layer3
  1,
  // Layer2
  4
  // Layer1
];
function R_(r, e, t, i, s) {
  if (t + 24 > e.length)
    return;
  const n = I_(e, t);
  if (n && t + n.frameLength <= e.length) {
    const a = n.samplesPerFrame * 9e4 / n.sampleRate, o = i + s * a, c = {
      unit: e.subarray(t, t + n.frameLength),
      pts: o,
      dts: o
    };
    return r.config = [], r.channelCount = n.channelCount, r.samplerate = n.sampleRate, r.samples.push(c), {
      sample: c,
      length: n.frameLength,
      missing: 0
    };
  }
}
function I_(r, e) {
  const t = r[e + 1] >> 3 & 3, i = r[e + 1] >> 1 & 3, s = r[e + 2] >> 4 & 15, n = r[e + 2] >> 2 & 3;
  if (t !== 1 && s !== 0 && s !== 15 && n !== 3) {
    const a = r[e + 2] >> 1 & 1, o = r[e + 3] >> 6, c = t === 3 ? 3 - i : i === 3 ? 3 : 4, l = w8[c * 14 + s - 1] * 1e3, h = M8[(t === 3 ? 0 : t === 2 ? 1 : 2) * 3 + n], u = o === 3 ? 1 : 2, f = B8[t][i], p = F8[i], m = f * 8 * p, g = Math.floor(f * l / h + a) * p;
    if (ta === null) {
      const v = (navigator.userAgent || "").match(/Chrome\/(\d+)/i);
      ta = v ? parseInt(v[1]) : 0;
    }
    return !!ta && ta <= 87 && i === 2 && l >= 224e3 && o === 0 && (r[e + 3] = r[e + 3] | 128), {
      sampleRate: h,
      channelCount: u,
      frameLength: g,
      samplesPerFrame: m
    };
  }
}
function eh(r, e) {
  return r[e] === 255 && (r[e + 1] & 224) === 224 && (r[e + 1] & 6) !== 0;
}
function L_(r, e) {
  return e + 1 < r.length && eh(r, e);
}
function O8(r, e) {
  return eh(r, e) && 4 <= r.length - e;
}
function D_(r, e) {
  if (e + 1 < r.length && eh(r, e)) {
    const i = I_(r, e);
    let s = 4;
    i != null && i.frameLength && (s = i.frameLength);
    const n = e + s;
    return n === r.length || L_(r, n);
  }
  return !1;
}
class N8 extends qd {
  constructor(e, t) {
    super(), this.observer = void 0, this.config = void 0, this.observer = e, this.config = t;
  }
  resetInitSegment(e, t, i, s) {
    super.resetInitSegment(e, t, i, s), this._audioTrack = {
      container: "audio/adts",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "aac",
      samples: [],
      manifestCodec: t,
      duration: s,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  static probe(e, t) {
    if (!e)
      return !1;
    const i = Tn(e, 0);
    let s = (i == null ? void 0 : i.length) || 0;
    if (D_(e, s))
      return !1;
    for (let n = e.length; s < n; s++)
      if (_8(e, s))
        return t.log("ADTS sync word found !"), !0;
    return !1;
  }
  canParse(e, t) {
    return g8(e, t);
  }
  appendFrame(e, t, i) {
    S_(e, this.observer, t, i, e.manifestCodec);
    const s = b_(e, t, i, this.basePTS, this.frameIndex);
    if (s && s.missing === 0)
      return s;
  }
}
const P_ = (r, e) => {
  let t = 0, i = 5;
  e += i;
  const s = new Uint32Array(1), n = new Uint32Array(1), a = new Uint8Array(1);
  for (; i > 0; ) {
    a[0] = r[e];
    const o = Math.min(i, 8), c = 8 - o;
    n[0] = 4278190080 >>> 24 + c << c, s[0] = (a[0] & n[0]) >> c, t = t ? t << o | s[0] : s[0], e += 1, i -= o;
  }
  return t;
};
class G8 extends qd {
  constructor(e) {
    super(), this.observer = void 0, this.observer = e;
  }
  resetInitSegment(e, t, i, s) {
    super.resetInitSegment(e, t, i, s), this._audioTrack = {
      container: "audio/ac-3",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "ac3",
      samples: [],
      manifestCodec: t,
      duration: s,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  canParse(e, t) {
    return t + 64 < e.length;
  }
  appendFrame(e, t, i) {
    const s = k_(e, t, i, this.basePTS, this.frameIndex);
    if (s !== -1)
      return {
        sample: e.samples[e.samples.length - 1],
        length: s,
        missing: 0
      };
  }
  static probe(e) {
    if (!e)
      return !1;
    const t = Tn(e, 0);
    if (!t)
      return !1;
    const i = t.length;
    return e[i] === 11 && e[i + 1] === 119 && Jd(t) !== void 0 && // check the bsid to confirm ac-3
    P_(e, i) < 16;
  }
}
function k_(r, e, t, i, s) {
  if (t + 8 > e.length || e[t] !== 11 || e[t + 1] !== 119)
    return -1;
  const n = e[t + 4] >> 6;
  if (n >= 3)
    return -1;
  const o = [48e3, 44100, 32e3][n], c = e[t + 4] & 63, d = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920][c * 3 + n] * 2;
  if (t + d > e.length)
    return -1;
  const h = e[t + 6] >> 5;
  let u = 0;
  h === 2 ? u += 2 : (h & 1 && h !== 1 && (u += 2), h & 4 && (u += 2));
  const f = (e[t + 6] << 8 | e[t + 7]) >> 12 - u & 1, m = [2, 1, 2, 3, 3, 4, 4, 5][h] + f, g = e[t + 5] >> 3, x = e[t + 5] & 7, _ = new Uint8Array([n << 6 | g << 1 | x >> 2, (x & 3) << 6 | h << 3 | f << 2 | c >> 4, c << 4 & 224]), v = 1536 / o * 9e4, E = i + s * v, b = e.subarray(t, t + d);
  return r.config = _, r.channelCount = m, r.samplerate = o, r.samples.push({
    unit: b,
    pts: E
  }), d;
}
class U8 extends qd {
  resetInitSegment(e, t, i, s) {
    super.resetInitSegment(e, t, i, s), this._audioTrack = {
      container: "audio/mpeg",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "mp3",
      samples: [],
      manifestCodec: t,
      duration: s,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  static probe(e) {
    if (!e)
      return !1;
    const t = Tn(e, 0);
    let i = (t == null ? void 0 : t.length) || 0;
    if (t && e[i] === 11 && e[i + 1] === 119 && Jd(t) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
    P_(e, i) <= 16)
      return !1;
    for (let s = e.length; i < s; i++)
      if (D_(e, i))
        return Pe.log("MPEG Audio sync word found !"), !0;
    return !1;
  }
  canParse(e, t) {
    return O8(e, t);
  }
  appendFrame(e, t, i) {
    if (this.basePTS !== null)
      return R_(e, t, i, this.basePTS, this.frameIndex);
  }
}
const V8 = /\/emsg[-/]ID3/i;
class W8 {
  constructor(e, t) {
    this.remainderData = null, this.timeOffset = 0, this.config = void 0, this.videoTrack = void 0, this.audioTrack = void 0, this.id3Track = void 0, this.txtTrack = void 0, this.config = t;
  }
  resetTimeStamp() {
  }
  resetInitSegment(e, t, i, s) {
    const n = this.videoTrack = Ci("video", 1), a = this.audioTrack = Ci("audio", 1), o = this.txtTrack = Ci("text", 1);
    if (this.id3Track = Ci("id3", 1), this.timeOffset = 0, !(e != null && e.byteLength))
      return;
    const c = Xg(e);
    if (c.video) {
      const {
        id: l,
        timescale: d,
        codec: h,
        supplemental: u
      } = c.video;
      n.id = l, n.timescale = o.timescale = d, n.codec = h, n.supplemental = u;
    }
    if (c.audio) {
      const {
        id: l,
        timescale: d,
        codec: h
      } = c.audio;
      a.id = l, a.timescale = d, a.codec = h;
    }
    o.id = Zg.text, n.sampleDuration = 0, n.duration = a.duration = s;
  }
  resetContiguity() {
    this.remainderData = null;
  }
  static probe(e) {
    return U4(e);
  }
  demux(e, t) {
    this.timeOffset = t;
    let i = e;
    const s = this.videoTrack, n = this.txtTrack;
    if (this.config.progressive) {
      this.remainderData && (i = Qt(this.remainderData, e));
      const o = K4(i);
      this.remainderData = o.remainder, s.samples = o.valid || new Uint8Array();
    } else
      s.samples = i;
    const a = this.extractID3Track(s, t);
    return n.samples = jf(t, s), {
      videoTrack: s,
      audioTrack: this.audioTrack,
      id3Track: a,
      textTrack: this.txtTrack
    };
  }
  flush() {
    const e = this.timeOffset, t = this.videoTrack, i = this.txtTrack;
    t.samples = this.remainderData || new Uint8Array(), this.remainderData = null;
    const s = this.extractID3Track(t, this.timeOffset);
    return i.samples = jf(e, t), {
      videoTrack: t,
      audioTrack: Ci(),
      id3Track: s,
      textTrack: Ci()
    };
  }
  extractID3Track(e, t) {
    const i = this.id3Track;
    if (e.samples.length) {
      const s = pe(e.samples, ["emsg"]);
      s && s.forEach((n) => {
        const a = Y4(n);
        if (V8.test(a.schemeIdUri)) {
          const o = kp(a, t);
          let c = a.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : a.eventDuration / a.timeScale;
          c <= 1e-3 && (c = Number.POSITIVE_INFINITY);
          const l = a.payload;
          i.samples.push({
            data: l,
            len: l.byteLength,
            dts: o,
            pts: o,
            type: Ht.emsg,
            duration: c
          });
        } else if (this.config.enableEmsgKLVMetadata && a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
          const o = kp(a, t);
          i.samples.push({
            data: a.payload,
            len: a.payload.byteLength,
            dts: o,
            pts: o,
            type: Ht.misbklv,
            duration: Number.POSITIVE_INFINITY
          });
        }
      });
    }
    return i;
  }
  demuxSampleAes(e, t, i) {
    return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"));
  }
  destroy() {
    this.config = null, this.remainderData = null, this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = void 0;
  }
}
function kp(r, e) {
  return q(r.presentationTime) ? r.presentationTime / r.timeScale : e + r.presentationTimeDelta / r.timeScale;
}
class H8 {
  constructor(e, t, i) {
    this.keyData = void 0, this.decrypter = void 0, this.keyData = i, this.decrypter = new Zd(t, {
      removePKCS7Padding: !1
    });
  }
  decryptBuffer(e) {
    return this.decrypter.decrypt(e, this.keyData.key.buffer, this.keyData.iv.buffer, xs.cbc);
  }
  // AAC - encrypt all full 16 bytes blocks starting from offset 16
  decryptAacSample(e, t, i) {
    const s = e[t].unit;
    if (s.length <= 16)
      return;
    const n = s.subarray(16, s.length - s.length % 16), a = n.buffer.slice(n.byteOffset, n.byteOffset + n.length);
    this.decryptBuffer(a).then((o) => {
      const c = new Uint8Array(o);
      s.set(c, 16), this.decrypter.isSync() || this.decryptAacSamples(e, t + 1, i);
    }).catch(i);
  }
  decryptAacSamples(e, t, i) {
    for (; ; t++) {
      if (t >= e.length) {
        i();
        return;
      }
      if (!(e[t].unit.length < 32) && (this.decryptAacSample(e, t, i), !this.decrypter.isSync()))
        return;
    }
  }
  // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  getAvcEncryptedData(e) {
    const t = Math.floor((e.length - 48) / 160) * 16 + 16, i = new Int8Array(t);
    let s = 0;
    for (let n = 32; n < e.length - 16; n += 160, s += 16)
      i.set(e.subarray(n, n + 16), s);
    return i;
  }
  getAvcDecryptedUnit(e, t) {
    const i = new Uint8Array(t);
    let s = 0;
    for (let n = 32; n < e.length - 16; n += 160, s += 16)
      e.set(i.subarray(s, s + 16), n);
    return e;
  }
  decryptAvcSample(e, t, i, s, n) {
    const a = zg(n.data), o = this.getAvcEncryptedData(a);
    this.decryptBuffer(o.buffer).then((c) => {
      n.data = this.getAvcDecryptedUnit(a, c), this.decrypter.isSync() || this.decryptAvcSamples(e, t, i + 1, s);
    }).catch(s);
  }
  decryptAvcSamples(e, t, i, s) {
    if (e instanceof Uint8Array)
      throw new Error("Cannot decrypt samples of type Uint8Array");
    for (; ; t++, i = 0) {
      if (t >= e.length) {
        s();
        return;
      }
      const n = e[t].units;
      for (; !(i >= n.length); i++) {
        const a = n[i];
        if (!(a.data.length <= 48 || a.type !== 1 && a.type !== 5) && (this.decryptAvcSample(e, t, i, s, a), !this.decrypter.isSync()))
          return;
      }
    }
  }
}
class w_ {
  constructor() {
    this.VideoSample = null;
  }
  createVideoSample(e, t, i) {
    return {
      key: e,
      frame: !1,
      pts: t,
      dts: i,
      units: [],
      length: 0
    };
  }
  getLastNalUnit(e) {
    var t;
    let i = this.VideoSample, s;
    if ((!i || i.units.length === 0) && (i = e[e.length - 1]), (t = i) != null && t.units) {
      const n = i.units;
      s = n[n.length - 1];
    }
    return s;
  }
  pushAccessUnit(e, t) {
    if (e.units.length && e.frame) {
      if (e.pts === void 0) {
        const i = t.samples, s = i.length;
        if (s) {
          const n = i[s - 1];
          e.pts = n.pts, e.dts = n.dts;
        } else {
          t.dropped++;
          return;
        }
      }
      t.samples.push(e);
    }
  }
  parseNALu(e, t, i) {
    const s = t.byteLength;
    let n = e.naluState || 0;
    const a = n, o = [];
    let c = 0, l, d, h, u = -1, f = 0;
    for (n === -1 && (u = 0, f = this.getNALuType(t, 0), n = 0, c = 1); c < s; ) {
      if (l = t[c++], !n) {
        n = l ? 0 : 1;
        continue;
      }
      if (n === 1) {
        n = l ? 0 : 2;
        continue;
      }
      if (!l)
        n = 3;
      else if (l === 1) {
        if (d = c - n - 1, u >= 0) {
          const p = {
            data: t.subarray(u, d),
            type: f
          };
          o.push(p);
        } else {
          const p = this.getLastNalUnit(e.samples);
          p && (a && c <= 4 - a && p.state && (p.data = p.data.subarray(0, p.data.byteLength - a)), d > 0 && (p.data = Qt(p.data, t.subarray(0, d)), p.state = 0));
        }
        c < s ? (h = this.getNALuType(t, c), u = c, f = h, n = 0) : n = -1;
      } else
        n = 0;
    }
    if (u >= 0 && n >= 0) {
      const p = {
        data: t.subarray(u, s),
        type: f,
        state: n
      };
      o.push(p);
    }
    if (o.length === 0) {
      const p = this.getLastNalUnit(e.samples);
      p && (p.data = Qt(p.data, t));
    }
    return e.naluState = n, o;
  }
}
class cn {
  constructor(e) {
    this.data = void 0, this.bytesAvailable = void 0, this.word = void 0, this.bitsAvailable = void 0, this.data = e, this.bytesAvailable = e.byteLength, this.word = 0, this.bitsAvailable = 0;
  }
  // ():void
  loadWord() {
    const e = this.data, t = this.bytesAvailable, i = e.byteLength - t, s = new Uint8Array(4), n = Math.min(4, t);
    if (n === 0)
      throw new Error("no bytes available");
    s.set(e.subarray(i, i + n)), this.word = new DataView(s.buffer).getUint32(0), this.bitsAvailable = n * 8, this.bytesAvailable -= n;
  }
  // (count:int):void
  skipBits(e) {
    let t;
    e = Math.min(e, this.bytesAvailable * 8 + this.bitsAvailable), this.bitsAvailable > e ? (this.word <<= e, this.bitsAvailable -= e) : (e -= this.bitsAvailable, t = e >> 3, e -= t << 3, this.bytesAvailable -= t, this.loadWord(), this.word <<= e, this.bitsAvailable -= e);
  }
  // (size:int):uint
  readBits(e) {
    let t = Math.min(this.bitsAvailable, e);
    const i = this.word >>> 32 - t;
    if (e > 32 && Pe.error("Cannot read more than 32 bits at a time"), this.bitsAvailable -= t, this.bitsAvailable > 0)
      this.word <<= t;
    else if (this.bytesAvailable > 0)
      this.loadWord();
    else
      throw new Error("no bits available");
    return t = e - t, t > 0 && this.bitsAvailable ? i << t | this.readBits(t) : i;
  }
  // ():uint
  skipLZ() {
    let e;
    for (e = 0; e < this.bitsAvailable; ++e)
      if (this.word & 2147483648 >>> e)
        return this.word <<= e, this.bitsAvailable -= e, e;
    return this.loadWord(), e + this.skipLZ();
  }
  // ():void
  skipUEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():void
  skipEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():uint
  readUEG() {
    const e = this.skipLZ();
    return this.readBits(e + 1) - 1;
  }
  // ():int
  readEG() {
    const e = this.readUEG();
    return 1 & e ? 1 + e >>> 1 : -1 * (e >>> 1);
  }
  // Some convenience functions
  // :Boolean
  readBoolean() {
    return this.readBits(1) === 1;
  }
  // ():int
  readUByte() {
    return this.readBits(8);
  }
  // ():int
  readUShort() {
    return this.readBits(16);
  }
  // ():int
  readUInt() {
    return this.readBits(32);
  }
}
class Z8 extends w_ {
  parsePES(e, t, i, s) {
    const n = this.parseNALu(e, i.data, s);
    let a = this.VideoSample, o, c = !1;
    i.data = null, a && n.length && !e.audFound && (this.pushAccessUnit(a, e), a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts)), n.forEach((l) => {
      var d, h;
      switch (l.type) {
        case 1: {
          let m = !1;
          o = !0;
          const g = l.data;
          if (c && g.length > 4) {
            const x = this.readSliceType(g);
            (x === 2 || x === 4 || x === 7 || x === 9) && (m = !0);
          }
          if (m) {
            var u;
            (u = a) != null && u.frame && !a.key && (this.pushAccessUnit(a, e), a = this.VideoSample = null);
          }
          a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.frame = !0, a.key = m;
          break;
        }
        case 5:
          o = !0, (d = a) != null && d.frame && !a.key && (this.pushAccessUnit(a, e), a = this.VideoSample = null), a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.key = !0, a.frame = !0;
          break;
        case 6: {
          o = !0, Ud(l.data, 1, i.pts, t.samples);
          break;
        }
        case 7: {
          var f, p;
          o = !0, c = !0;
          const m = l.data, g = this.readSPS(m);
          if (!e.sps || e.width !== g.width || e.height !== g.height || ((f = e.pixelRatio) == null ? void 0 : f[0]) !== g.pixelRatio[0] || ((p = e.pixelRatio) == null ? void 0 : p[1]) !== g.pixelRatio[1]) {
            e.width = g.width, e.height = g.height, e.pixelRatio = g.pixelRatio, e.sps = [m];
            const x = m.subarray(1, 4);
            let _ = "avc1.";
            for (let v = 0; v < 3; v++) {
              let E = x[v].toString(16);
              E.length < 2 && (E = "0" + E), _ += E;
            }
            e.codec = _;
          }
          break;
        }
        case 8:
          o = !0, e.pps = [l.data];
          break;
        case 9:
          o = !0, e.audFound = !0, (h = a) != null && h.frame && (this.pushAccessUnit(a, e), a = null), a || (a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts));
          break;
        case 12:
          o = !0;
          break;
        default:
          o = !1;
          break;
      }
      a && o && a.units.push(l);
    }), s && a && (this.pushAccessUnit(a, e), this.VideoSample = null);
  }
  getNALuType(e, t) {
    return e[t] & 31;
  }
  readSliceType(e) {
    const t = new cn(e);
    return t.readUByte(), t.readUEG(), t.readUEG();
  }
  /**
   * The scaling list is optionally transmitted as part of a sequence parameter
   * set and is not relevant to transmuxing.
   * @param count the number of entries in this scaling list
   * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
   */
  skipScalingList(e, t) {
    let i = 8, s = 8, n;
    for (let a = 0; a < e; a++)
      s !== 0 && (n = t.readEG(), s = (i + n + 256) % 256), i = s === 0 ? i : s;
  }
  /**
   * Read a sequence parameter set and return some interesting video
   * properties. A sequence parameter set is the H264 metadata that
   * describes the properties of upcoming video frames.
   * @returns an object with configuration parsed from the
   * sequence parameter set, including the dimensions of the
   * associated video frames.
   */
  readSPS(e) {
    const t = new cn(e);
    let i = 0, s = 0, n = 0, a = 0, o, c, l;
    const d = t.readUByte.bind(t), h = t.readBits.bind(t), u = t.readUEG.bind(t), f = t.readBoolean.bind(t), p = t.skipBits.bind(t), m = t.skipEG.bind(t), g = t.skipUEG.bind(t), x = this.skipScalingList.bind(this);
    d();
    const _ = d();
    if (h(5), p(3), d(), g(), _ === 100 || _ === 110 || _ === 122 || _ === 244 || _ === 44 || _ === 83 || _ === 86 || _ === 118 || _ === 128) {
      const I = u();
      if (I === 3 && p(1), g(), g(), p(1), f())
        for (c = I !== 3 ? 8 : 12, l = 0; l < c; l++)
          f() && (l < 6 ? x(16, t) : x(64, t));
    }
    g();
    const v = u();
    if (v === 0)
      u();
    else if (v === 1)
      for (p(1), m(), m(), o = u(), l = 0; l < o; l++)
        m();
    g(), p(1);
    const E = u(), b = u(), A = h(1);
    A === 0 && p(1), p(1), f() && (i = u(), s = u(), n = u(), a = u());
    let C = [1, 1];
    if (f() && f())
      switch (d()) {
        case 1:
          C = [1, 1];
          break;
        case 2:
          C = [12, 11];
          break;
        case 3:
          C = [10, 11];
          break;
        case 4:
          C = [16, 11];
          break;
        case 5:
          C = [40, 33];
          break;
        case 6:
          C = [24, 11];
          break;
        case 7:
          C = [20, 11];
          break;
        case 8:
          C = [32, 11];
          break;
        case 9:
          C = [80, 33];
          break;
        case 10:
          C = [18, 11];
          break;
        case 11:
          C = [15, 11];
          break;
        case 12:
          C = [64, 33];
          break;
        case 13:
          C = [160, 99];
          break;
        case 14:
          C = [4, 3];
          break;
        case 15:
          C = [3, 2];
          break;
        case 16:
          C = [2, 1];
          break;
        case 255: {
          C = [d() << 8 | d(), d() << 8 | d()];
          break;
        }
      }
    return {
      width: Math.ceil((E + 1) * 16 - i * 2 - s * 2),
      height: (2 - A) * (b + 1) * 16 - (A ? 2 : 4) * (n + a),
      pixelRatio: C
    };
  }
}
class $8 extends w_ {
  constructor(...e) {
    super(...e), this.initVPS = null;
  }
  parsePES(e, t, i, s) {
    const n = this.parseNALu(e, i.data, s);
    let a = this.VideoSample, o, c = !1;
    i.data = null, a && n.length && !e.audFound && (this.pushAccessUnit(a, e), a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts)), n.forEach((l) => {
      var d, h;
      switch (l.type) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          a || (a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts)), a.frame = !0, o = !0;
          break;
        case 16:
        case 17:
        case 18:
        case 21:
          if (o = !0, c) {
            var u;
            (u = a) != null && u.frame && !a.key && (this.pushAccessUnit(a, e), a = this.VideoSample = null);
          }
          a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.key = !0, a.frame = !0;
          break;
        case 19:
        case 20:
          o = !0, (d = a) != null && d.frame && !a.key && (this.pushAccessUnit(a, e), a = this.VideoSample = null), a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.key = !0, a.frame = !0;
          break;
        case 39:
          o = !0, Ud(
            l.data,
            2,
            // NALu header size
            i.pts,
            t.samples
          );
          break;
        case 32:
          o = !0, e.vps || (typeof e.params != "object" && (e.params = {}), e.params = Me(e.params, this.readVPS(l.data)), this.initVPS = l.data), e.vps = [l.data];
          break;
        case 33:
          if (o = !0, c = !0, e.vps !== void 0 && e.vps[0] !== this.initVPS && e.sps !== void 0 && !this.matchSPS(e.sps[0], l.data) && (this.initVPS = e.vps[0], e.sps = e.pps = void 0), !e.sps) {
            const f = this.readSPS(l.data);
            e.width = f.width, e.height = f.height, e.pixelRatio = f.pixelRatio, e.codec = f.codecString, e.sps = [], typeof e.params != "object" && (e.params = {});
            for (const p in f.params)
              e.params[p] = f.params[p];
          }
          this.pushParameterSet(e.sps, l.data, e.vps), a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.key = !0;
          break;
        case 34:
          if (o = !0, typeof e.params == "object") {
            if (!e.pps) {
              e.pps = [];
              const f = this.readPPS(l.data);
              for (const p in f)
                e.params[p] = f[p];
            }
            this.pushParameterSet(e.pps, l.data, e.vps);
          }
          break;
        case 35:
          o = !0, e.audFound = !0, (h = a) != null && h.frame && (this.pushAccessUnit(a, e), a = null), a || (a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts));
          break;
        default:
          o = !1;
          break;
      }
      a && o && a.units.push(l);
    }), s && a && (this.pushAccessUnit(a, e), this.VideoSample = null);
  }
  pushParameterSet(e, t, i) {
    (i && i[0] === this.initVPS || !i && !e.length) && e.push(t);
  }
  getNALuType(e, t) {
    return (e[t] & 126) >>> 1;
  }
  ebsp2rbsp(e) {
    const t = new Uint8Array(e.byteLength);
    let i = 0;
    for (let s = 0; s < e.byteLength; s++)
      s >= 2 && e[s] === 3 && e[s - 1] === 0 && e[s - 2] === 0 || (t[i] = e[s], i++);
    return new Uint8Array(t.buffer, 0, i);
  }
  pushAccessUnit(e, t) {
    super.pushAccessUnit(e, t), this.initVPS && (this.initVPS = null);
  }
  readVPS(e) {
    const t = new cn(e);
    t.readUByte(), t.readUByte(), t.readBits(4), t.skipBits(2), t.readBits(6);
    const i = t.readBits(3), s = t.readBoolean();
    return {
      numTemporalLayers: i + 1,
      temporalIdNested: s
    };
  }
  readSPS(e) {
    const t = new cn(this.ebsp2rbsp(e));
    t.readUByte(), t.readUByte(), t.readBits(4);
    const i = t.readBits(3);
    t.readBoolean();
    const s = t.readBits(2), n = t.readBoolean(), a = t.readBits(5), o = t.readUByte(), c = t.readUByte(), l = t.readUByte(), d = t.readUByte(), h = t.readUByte(), u = t.readUByte(), f = t.readUByte(), p = t.readUByte(), m = t.readUByte(), g = t.readUByte(), x = t.readUByte(), _ = [], v = [];
    for (let ee = 0; ee < i; ee++)
      _.push(t.readBoolean()), v.push(t.readBoolean());
    if (i > 0)
      for (let ee = i; ee < 8; ee++)
        t.readBits(2);
    for (let ee = 0; ee < i; ee++)
      _[ee] && (t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte(), t.readUByte()), v[ee] && t.readUByte();
    t.readUEG();
    const E = t.readUEG();
    E == 3 && t.skipBits(1);
    const b = t.readUEG(), A = t.readUEG(), C = t.readBoolean();
    let I = 0, L = 0, R = 0, D = 0;
    C && (I += t.readUEG(), L += t.readUEG(), R += t.readUEG(), D += t.readUEG());
    const M = t.readUEG(), w = t.readUEG(), N = t.readUEG(), H = t.readBoolean();
    for (let ee = H ? 0 : i; ee <= i; ee++)
      t.skipUEG(), t.skipUEG(), t.skipUEG();
    if (t.skipUEG(), t.skipUEG(), t.skipUEG(), t.skipUEG(), t.skipUEG(), t.skipUEG(), t.readBoolean() && t.readBoolean())
      for (let xe = 0; xe < 4; xe++)
        for (let Ee = 0; Ee < (xe === 3 ? 2 : 6); Ee++)
          if (!t.readBoolean())
            t.readUEG();
          else {
            const Ie = Math.min(64, 1 << 4 + (xe << 1));
            xe > 1 && t.readEG();
            for (let Ve = 0; Ve < Ie; Ve++)
              t.readEG();
          }
    t.readBoolean(), t.readBoolean(), t.readBoolean() && (t.readUByte(), t.skipUEG(), t.skipUEG(), t.readBoolean());
    const $ = t.readUEG();
    let Y = 0;
    for (let ee = 0; ee < $; ee++) {
      let xe = !1;
      if (ee !== 0 && (xe = t.readBoolean()), xe) {
        ee === $ && t.readUEG(), t.readBoolean(), t.readUEG();
        let Ee = 0;
        for (let tt = 0; tt <= Y; tt++) {
          const Ie = t.readBoolean();
          let Ve = !1;
          Ie || (Ve = t.readBoolean()), (Ie || Ve) && Ee++;
        }
        Y = Ee;
      } else {
        const Ee = t.readUEG(), tt = t.readUEG();
        Y = Ee + tt;
        for (let Ie = 0; Ie < Ee; Ie++)
          t.readUEG(), t.readBoolean();
        for (let Ie = 0; Ie < tt; Ie++)
          t.readUEG(), t.readBoolean();
      }
    }
    if (t.readBoolean()) {
      const ee = t.readUEG();
      for (let xe = 0; xe < ee; xe++) {
        for (let Ee = 0; Ee < N + 4; Ee++)
          t.readBits(1);
        t.readBits(1);
      }
    }
    let k = 0, P = 1, B = 1, O = !0, j = 1, Q = 0;
    t.readBoolean(), t.readBoolean();
    let ne = !1;
    if (t.readBoolean()) {
      if (t.readBoolean()) {
        const ke = t.readUByte(), Rt = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], Et = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
        ke > 0 && ke < 16 ? (P = Rt[ke - 1], B = Et[ke - 1]) : ke === 255 && (P = t.readBits(16), B = t.readBits(16));
      }
      if (t.readBoolean() && t.readBoolean(), t.readBoolean() && (t.readBits(3), t.readBoolean(), t.readBoolean() && (t.readUByte(), t.readUByte(), t.readUByte())), t.readBoolean() && (t.readUEG(), t.readUEG()), t.readBoolean(), t.readBoolean(), t.readBoolean(), ne = t.readBoolean(), ne && (t.skipUEG(), t.skipUEG(), t.skipUEG(), t.skipUEG()), t.readBoolean() && (j = t.readBits(32), Q = t.readBits(32), t.readBoolean() && t.readUEG(), t.readBoolean())) {
        const Et = t.readBoolean(), Fi = t.readBoolean();
        let lt = !1;
        (Et || Fi) && (lt = t.readBoolean(), lt && (t.readUByte(), t.readBits(5), t.readBoolean(), t.readBits(5)), t.readBits(4), t.readBits(4), lt && t.readBits(4), t.readBits(5), t.readBits(5), t.readBits(5));
        for (let ei = 0; ei <= i; ei++) {
          O = t.readBoolean();
          const js = O || t.readBoolean();
          let es = !1;
          js ? t.readEG() : es = t.readBoolean();
          const Oi = es ? 1 : t.readUEG() + 1;
          if (Et)
            for (let St = 0; St < Oi; St++)
              t.readUEG(), t.readUEG(), lt && (t.readUEG(), t.readUEG()), t.skipBits(1);
          if (Fi)
            for (let St = 0; St < Oi; St++)
              t.readUEG(), t.readUEG(), lt && (t.readUEG(), t.readUEG()), t.skipBits(1);
        }
      }
      t.readBoolean() && (t.readBoolean(), t.readBoolean(), t.readBoolean(), k = t.readUEG());
    }
    let Se = b, Ce = A;
    if (C) {
      let ee = 1, xe = 1;
      E === 1 ? ee = xe = 2 : E == 2 && (ee = 2), Se = b - ee * L - ee * I, Ce = A - xe * D - xe * R;
    }
    const Te = s ? ["A", "B", "C"][s] : "", Xe = o << 24 | c << 16 | l << 8 | d;
    let be = 0;
    for (let ee = 0; ee < 32; ee++)
      be = (be | (Xe >> ee & 1) << 31 - ee) >>> 0;
    let Re = be.toString(16);
    return a === 1 && Re === "2" && (Re = "6"), {
      codecString: `hvc1.${Te}${a}.${Re}.${n ? "H" : "L"}${x}.B0`,
      params: {
        general_tier_flag: n,
        general_profile_idc: a,
        general_profile_space: s,
        general_profile_compatibility_flags: [o, c, l, d],
        general_constraint_indicator_flags: [h, u, f, p, m, g],
        general_level_idc: x,
        bit_depth: M + 8,
        bit_depth_luma_minus8: M,
        bit_depth_chroma_minus8: w,
        min_spatial_segmentation_idc: k,
        chroma_format_idc: E,
        frame_rate: {
          fixed: O,
          fps: Q / j
        }
      },
      width: Se,
      height: Ce,
      pixelRatio: [P, B]
    };
  }
  readPPS(e) {
    const t = new cn(this.ebsp2rbsp(e));
    t.readUByte(), t.readUByte(), t.skipUEG(), t.skipUEG(), t.skipBits(2), t.skipBits(3), t.skipBits(2), t.skipUEG(), t.skipUEG(), t.skipEG(), t.skipBits(2), t.readBoolean() && t.skipUEG(), t.skipEG(), t.skipEG(), t.skipBits(4);
    const s = t.readBoolean(), n = t.readBoolean();
    let a = 1;
    return n && s ? a = 0 : n ? a = 3 : s && (a = 2), {
      parallelismType: a
    };
  }
  matchSPS(e, t) {
    return String.fromCharCode.apply(null, e).substr(3) === String.fromCharCode.apply(null, t).substr(3);
  }
}
const ct = 188;
class os {
  constructor(e, t, i, s) {
    this.logger = void 0, this.observer = void 0, this.config = void 0, this.typeSupported = void 0, this.sampleAes = null, this.pmtParsed = !1, this.audioCodec = void 0, this.videoCodec = void 0, this._pmtId = -1, this._videoTrack = void 0, this._audioTrack = void 0, this._id3Track = void 0, this._txtTrack = void 0, this.aacOverFlow = null, this.remainderData = null, this.videoParser = void 0, this.observer = e, this.config = t, this.typeSupported = i, this.logger = s, this.videoParser = null;
  }
  static probe(e, t) {
    const i = os.syncOffset(e);
    return i > 0 && t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`), i !== -1;
  }
  static syncOffset(e) {
    const t = e.length;
    let i = Math.min(ct * 5, t - ct) + 1, s = 0;
    for (; s < i; ) {
      let n = !1, a = -1, o = 0;
      for (let c = s; c < t; c += ct)
        if (e[c] === 71 && (t - c === ct || e[c + ct] === 71)) {
          if (o++, a === -1 && (a = c, a !== 0 && (i = Math.min(a + ct * 99, e.length - ct) + 1)), n || (n = Oc(e, c) === 0), n && o > 1 && (a === 0 && o > 2 || c + ct > i))
            return a;
        } else {
          if (o)
            return -1;
          break;
        }
      s++;
    }
    return -1;
  }
  /**
   * Creates a track model internal to demuxer used to drive remuxing input
   */
  static createTrack(e, t) {
    return {
      container: e === "video" || e === "audio" ? "video/mp2t" : void 0,
      type: e,
      id: Zg[e],
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0,
      duration: e === "audio" ? t : void 0
    };
  }
  /**
   * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
   * Resets all internal track instances of the demuxer.
   */
  resetInitSegment(e, t, i, s) {
    this.pmtParsed = !1, this._pmtId = -1, this._videoTrack = os.createTrack("video"), this._videoTrack.duration = s, this._audioTrack = os.createTrack("audio", s), this._id3Track = os.createTrack("id3"), this._txtTrack = os.createTrack("text"), this._audioTrack.segmentCodec = "aac", this.videoParser = null, this.aacOverFlow = null, this.remainderData = null, this.audioCodec = t, this.videoCodec = i;
  }
  resetTimeStamp() {
  }
  resetContiguity() {
    const {
      _audioTrack: e,
      _videoTrack: t,
      _id3Track: i
    } = this;
    e && (e.pesData = null), t && (t.pesData = null), i && (i.pesData = null), this.aacOverFlow = null, this.remainderData = null;
  }
  demux(e, t, i = !1, s = !1) {
    i || (this.sampleAes = null);
    let n;
    const a = this._videoTrack, o = this._audioTrack, c = this._id3Track, l = this._txtTrack;
    let d = a.pid, h = a.pesData, u = o.pid, f = c.pid, p = o.pesData, m = c.pesData, g = null, x = this.pmtParsed, _ = this._pmtId, v = e.length;
    if (this.remainderData && (e = Qt(this.remainderData, e), v = e.length, this.remainderData = null), v < ct && !s)
      return this.remainderData = e, {
        audioTrack: o,
        videoTrack: a,
        id3Track: c,
        textTrack: l
      };
    const E = Math.max(0, os.syncOffset(e));
    v -= (v - E) % ct, v < e.byteLength && !s && (this.remainderData = new Uint8Array(e.buffer, v, e.buffer.byteLength - v));
    let b = 0;
    for (let C = E; C < v; C += ct)
      if (e[C] === 71) {
        const I = !!(e[C + 1] & 64), L = Oc(e, C), R = (e[C + 3] & 48) >> 4;
        let D;
        if (R > 1) {
          if (D = C + 5 + e[C + 4], D === C + ct)
            continue;
        } else
          D = C + 4;
        switch (L) {
          case d:
            I && (h && (n = sr(h, this.logger)) && (this.readyVideoParser(a.segmentCodec), this.videoParser !== null && this.videoParser.parsePES(a, l, n, !1)), h = {
              data: [],
              size: 0
            }), h && (h.data.push(e.subarray(D, C + ct)), h.size += C + ct - D);
            break;
          case u:
            if (I) {
              if (p && (n = sr(p, this.logger)))
                switch (o.segmentCodec) {
                  case "aac":
                    this.parseAACPES(o, n);
                    break;
                  case "mp3":
                    this.parseMPEGPES(o, n);
                    break;
                  case "ac3":
                    this.parseAC3PES(o, n);
                    break;
                }
              p = {
                data: [],
                size: 0
              };
            }
            p && (p.data.push(e.subarray(D, C + ct)), p.size += C + ct - D);
            break;
          case f:
            I && (m && (n = sr(m, this.logger)) && this.parseID3PES(c, n), m = {
              data: [],
              size: 0
            }), m && (m.data.push(e.subarray(D, C + ct)), m.size += C + ct - D);
            break;
          case 0:
            I && (D += e[D] + 1), _ = this._pmtId = K8(e, D);
            break;
          case _: {
            I && (D += e[D] + 1);
            const M = X8(e, D, this.typeSupported, i, this.observer, this.logger);
            d = M.videoPid, d > 0 && (a.pid = d, a.segmentCodec = M.segmentVideoCodec), u = M.audioPid, u > 0 && (o.pid = u, o.segmentCodec = M.segmentAudioCodec), f = M.id3Pid, f > 0 && (c.pid = f), g !== null && !x && (this.logger.warn(`MPEG-TS PMT found at ${C} after unknown PID '${g}'. Backtracking to sync byte @${E} to parse all TS packets.`), g = null, C = E - 188), x = this.pmtParsed = !0;
            break;
          }
          case 17:
          case 8191:
            break;
          default:
            g = L;
            break;
        }
      } else
        b++;
    b > 0 && Nc(this.observer, new Error(`Found ${b} TS packet/s that do not start with 0x47`), void 0, this.logger), a.pesData = h, o.pesData = p, c.pesData = m;
    const A = {
      audioTrack: o,
      videoTrack: a,
      id3Track: c,
      textTrack: l
    };
    return s && this.extractRemainingSamples(A), A;
  }
  flush() {
    const {
      remainderData: e
    } = this;
    this.remainderData = null;
    let t;
    return e ? t = this.demux(e, -1, !1, !0) : t = {
      videoTrack: this._videoTrack,
      audioTrack: this._audioTrack,
      id3Track: this._id3Track,
      textTrack: this._txtTrack
    }, this.extractRemainingSamples(t), this.sampleAes ? this.decrypt(t, this.sampleAes) : t;
  }
  extractRemainingSamples(e) {
    const {
      audioTrack: t,
      videoTrack: i,
      id3Track: s,
      textTrack: n
    } = e, a = i.pesData, o = t.pesData, c = s.pesData;
    let l;
    if (a && (l = sr(a, this.logger)) ? (this.readyVideoParser(i.segmentCodec), this.videoParser !== null && (this.videoParser.parsePES(i, n, l, !0), i.pesData = null)) : i.pesData = a, o && (l = sr(o, this.logger))) {
      switch (t.segmentCodec) {
        case "aac":
          this.parseAACPES(t, l);
          break;
        case "mp3":
          this.parseMPEGPES(t, l);
          break;
        case "ac3":
          this.parseAC3PES(t, l);
          break;
      }
      t.pesData = null;
    } else
      o != null && o.size && this.logger.log("last AAC PES packet truncated,might overlap between fragments"), t.pesData = o;
    c && (l = sr(c, this.logger)) ? (this.parseID3PES(s, l), s.pesData = null) : s.pesData = c;
  }
  demuxSampleAes(e, t, i) {
    const s = this.demux(e, i, !0, !this.config.progressive), n = this.sampleAes = new H8(this.observer, this.config, t);
    return this.decrypt(s, n);
  }
  readyVideoParser(e) {
    this.videoParser === null && (e === "avc" ? this.videoParser = new Z8() : e === "hevc" && (this.videoParser = new $8()));
  }
  decrypt(e, t) {
    return new Promise((i) => {
      const {
        audioTrack: s,
        videoTrack: n
      } = e;
      s.samples && s.segmentCodec === "aac" ? t.decryptAacSamples(s.samples, 0, () => {
        n.samples ? t.decryptAvcSamples(n.samples, 0, 0, () => {
          i(e);
        }) : i(e);
      }) : n.samples && t.decryptAvcSamples(n.samples, 0, 0, () => {
        i(e);
      });
    });
  }
  destroy() {
    this.observer && this.observer.removeAllListeners(), this.config = this.logger = this.observer = null, this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null, this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = void 0;
  }
  parseAACPES(e, t) {
    let i = 0;
    const s = this.aacOverFlow;
    let n = t.data;
    if (s) {
      this.aacOverFlow = null;
      const h = s.missing, u = s.sample.unit.byteLength;
      if (h === -1)
        n = Qt(s.sample.unit, n);
      else {
        const f = u - h;
        s.sample.unit.set(n.subarray(0, h), f), e.samples.push(s.sample), i = s.missing;
      }
    }
    let a, o;
    for (a = i, o = n.length; a < o - 1 && !lo(n, a); a++)
      ;
    if (a !== i) {
      let h;
      const u = a < o - 1;
      if (u ? h = `AAC PES did not start with ADTS header,offset:${a}` : h = "No ADTS header found in AAC PES", Nc(this.observer, new Error(h), u, this.logger), !u)
        return;
    }
    S_(e, this.observer, n, a, this.audioCodec);
    let c;
    if (t.pts !== void 0)
      c = t.pts;
    else if (s) {
      const h = T_(e.samplerate);
      c = s.sample.pts + h;
    } else {
      this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
      return;
    }
    let l = 0, d;
    for (; a < o; )
      if (d = b_(e, n, a, c, l), a += d.length, d.missing) {
        this.aacOverFlow = d;
        break;
      } else
        for (l++; a < o - 1 && !lo(n, a); a++)
          ;
  }
  parseMPEGPES(e, t) {
    const i = t.data, s = i.length;
    let n = 0, a = 0;
    const o = t.pts;
    if (o === void 0) {
      this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
      return;
    }
    for (; a < s; )
      if (L_(i, a)) {
        const c = R_(e, i, a, o, n);
        if (c)
          a += c.length, n++;
        else
          break;
      } else
        a++;
  }
  parseAC3PES(e, t) {
    {
      const i = t.data, s = t.pts;
      if (s === void 0) {
        this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");
        return;
      }
      const n = i.length;
      let a = 0, o = 0, c;
      for (; o < n && (c = k_(e, i, o, s, a++)) > 0; )
        o += c;
    }
  }
  parseID3PES(e, t) {
    if (t.pts === void 0) {
      this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
      return;
    }
    const i = Me({}, t, {
      type: this._videoTrack ? Ht.emsg : Ht.audioId3,
      duration: Number.POSITIVE_INFINITY
    });
    e.samples.push(i);
  }
}
function Oc(r, e) {
  return ((r[e + 1] & 31) << 8) + r[e + 2];
}
function K8(r, e) {
  return (r[e + 10] & 31) << 8 | r[e + 11];
}
function X8(r, e, t, i, s, n) {
  const a = {
    audioPid: -1,
    videoPid: -1,
    id3Pid: -1,
    segmentVideoCodec: "avc",
    segmentAudioCodec: "aac"
  }, o = (r[e + 1] & 15) << 8 | r[e + 2], c = e + 3 + o - 4, l = (r[e + 10] & 15) << 8 | r[e + 11];
  for (e += 12 + l; e < c; ) {
    const d = Oc(r, e), h = (r[e + 3] & 15) << 8 | r[e + 4];
    switch (r[e]) {
      case 207:
        if (!i) {
          A0("ADTS AAC", n);
          break;
        }
      case 15:
        a.audioPid === -1 && (a.audioPid = d);
        break;
      case 21:
        a.id3Pid === -1 && (a.id3Pid = d);
        break;
      case 219:
        if (!i) {
          A0("H.264", n);
          break;
        }
      case 27:
        a.videoPid === -1 && (a.videoPid = d);
        break;
      case 3:
      case 4:
        !t.mpeg && !t.mp3 ? n.log("MPEG audio found, not supported in this browser") : a.audioPid === -1 && (a.audioPid = d, a.segmentAudioCodec = "mp3");
        break;
      case 193:
        if (!i) {
          A0("AC-3", n);
          break;
        }
      case 129:
        t.ac3 ? a.audioPid === -1 && (a.audioPid = d, a.segmentAudioCodec = "ac3") : n.log("AC-3 audio found, not supported in this browser");
        break;
      case 6:
        if (a.audioPid === -1 && h > 0) {
          let u = e + 5, f = h;
          for (; f > 2; ) {
            switch (r[u]) {
              case 106:
                t.ac3 !== !0 ? n.log("AC-3 audio found, not supported in this browser for now") : (a.audioPid = d, a.segmentAudioCodec = "ac3");
                break;
            }
            const m = r[u + 1] + 2;
            u += m, f -= m;
          }
        }
        break;
      case 194:
      case 135:
        return Nc(s, new Error("Unsupported EC-3 in M2TS found"), void 0, n), a;
      case 36:
        a.videoPid === -1 && (a.videoPid = d, a.segmentVideoCodec = "hevc", n.log("HEVC in M2TS found"));
        break;
    }
    e += h + 5;
  }
  return a;
}
function Nc(r, e, t, i) {
  i.warn(`parsing error: ${e.message}`), r.emit(T.ERROR, T.ERROR, {
    type: ie.MEDIA_ERROR,
    details: V.FRAG_PARSING_ERROR,
    fatal: !1,
    levelRetry: t,
    error: e,
    reason: e.message
  });
}
function A0(r, e) {
  e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`);
}
function sr(r, e) {
  let t = 0, i, s, n, a, o;
  const c = r.data;
  if (!r || r.size === 0)
    return null;
  for (; c[0].length < 19 && c.length > 1; )
    c[0] = Qt(c[0], c[1]), c.splice(1, 1);
  if (i = c[0], (i[0] << 16) + (i[1] << 8) + i[2] === 1) {
    if (s = (i[4] << 8) + i[5], s && s > r.size - 6)
      return null;
    const d = i[7];
    d & 192 && (a = (i[9] & 14) * 536870912 + // 1 << 29
    (i[10] & 255) * 4194304 + // 1 << 22
    (i[11] & 254) * 16384 + // 1 << 14
    (i[12] & 255) * 128 + // 1 << 7
    (i[13] & 254) / 2, d & 64 ? (o = (i[14] & 14) * 536870912 + // 1 << 29
    (i[15] & 255) * 4194304 + // 1 << 22
    (i[16] & 254) * 16384 + // 1 << 14
    (i[17] & 255) * 128 + // 1 << 7
    (i[18] & 254) / 2, a - o > 60 * 9e4 && (e.warn(`${Math.round((a - o) / 9e4)}s delta between PTS and DTS, align them`), a = o)) : o = a), n = i[8];
    let h = n + 9;
    if (r.size <= h)
      return null;
    r.size -= h;
    const u = new Uint8Array(r.size);
    for (let f = 0, p = c.length; f < p; f++) {
      i = c[f];
      let m = i.byteLength;
      if (h)
        if (h > m) {
          h -= m;
          continue;
        } else
          i = i.subarray(h), m -= h, h = 0;
      u.set(i, t), t += m;
    }
    return s && (s -= n + 3), {
      data: u,
      pts: a,
      dts: o,
      len: s
    };
  }
  return null;
}
class Y8 {
  static getSilentFrame(e, t) {
    switch (e) {
      case "mp4a.40.2":
        if (t === 1)
          return new Uint8Array([0, 200, 0, 128, 35, 128]);
        if (t === 2)
          return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
        if (t === 3)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
        if (t === 4)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
        if (t === 5)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]);
        if (t === 6)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]);
        break;
      default:
        if (t === 1)
          return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
        if (t === 2)
          return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
        if (t === 3)
          return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]);
        break;
    }
  }
}
const ss = Math.pow(2, 32) - 1;
class U {
  static init() {
    U.types = {
      avc1: [],
      // codingname
      avcC: [],
      hvc1: [],
      hvcC: [],
      btrt: [],
      dinf: [],
      dref: [],
      esds: [],
      ftyp: [],
      hdlr: [],
      mdat: [],
      mdhd: [],
      mdia: [],
      mfhd: [],
      minf: [],
      moof: [],
      moov: [],
      mp4a: [],
      ".mp3": [],
      dac3: [],
      "ac-3": [],
      mvex: [],
      mvhd: [],
      pasp: [],
      sdtp: [],
      stbl: [],
      stco: [],
      stsc: [],
      stsd: [],
      stsz: [],
      stts: [],
      tfdt: [],
      tfhd: [],
      traf: [],
      trak: [],
      trun: [],
      trex: [],
      tkhd: [],
      vmhd: [],
      smhd: []
    };
    let e;
    for (e in U.types)
      U.types.hasOwnProperty(e) && (U.types[e] = [e.charCodeAt(0), e.charCodeAt(1), e.charCodeAt(2), e.charCodeAt(3)]);
    const t = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // pre_defined
      118,
      105,
      100,
      101,
      // handler_type: 'vide'
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      86,
      105,
      100,
      101,
      111,
      72,
      97,
      110,
      100,
      108,
      101,
      114,
      0
      // name: 'VideoHandler'
    ]), i = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // pre_defined
      115,
      111,
      117,
      110,
      // handler_type: 'soun'
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      83,
      111,
      117,
      110,
      100,
      72,
      97,
      110,
      100,
      108,
      101,
      114,
      0
      // name: 'SoundHandler'
    ]);
    U.HDLR_TYPES = {
      video: t,
      audio: i
    };
    const s = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      1,
      // entry_count
      0,
      0,
      0,
      12,
      // entry_size
      117,
      114,
      108,
      32,
      // 'url' type
      0,
      // version 0
      0,
      0,
      1
      // entry_flags
    ]), n = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0
      // entry_count
    ]);
    U.STTS = U.STSC = U.STCO = n, U.STSZ = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // sample_size
      0,
      0,
      0,
      0
      // sample_count
    ]), U.VMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      1,
      // flags
      0,
      0,
      // graphicsmode
      0,
      0,
      0,
      0,
      0,
      0
      // opcolor
    ]), U.SMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      // balance
      0,
      0
      // reserved
    ]), U.STSD = new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      1
    ]);
    const a = new Uint8Array([105, 115, 111, 109]), o = new Uint8Array([97, 118, 99, 49]), c = new Uint8Array([0, 0, 0, 1]);
    U.FTYP = U.box(U.types.ftyp, a, c, a, o), U.DINF = U.box(U.types.dinf, U.box(U.types.dref, s));
  }
  static box(e, ...t) {
    let i = 8, s = t.length;
    const n = s;
    for (; s--; )
      i += t[s].byteLength;
    const a = new Uint8Array(i);
    for (a[0] = i >> 24 & 255, a[1] = i >> 16 & 255, a[2] = i >> 8 & 255, a[3] = i & 255, a.set(e, 4), s = 0, i = 8; s < n; s++)
      a.set(t[s], i), i += t[s].byteLength;
    return a;
  }
  static hdlr(e) {
    return U.box(U.types.hdlr, U.HDLR_TYPES[e]);
  }
  static mdat(e) {
    return U.box(U.types.mdat, e);
  }
  static mdhd(e, t) {
    t *= e;
    const i = Math.floor(t / (ss + 1)), s = Math.floor(t % (ss + 1));
    return U.box(U.types.mdhd, new Uint8Array([
      1,
      // version 1
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      2,
      // creation_time
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      3,
      // modification_time
      e >> 24 & 255,
      e >> 16 & 255,
      e >> 8 & 255,
      e & 255,
      // timescale
      i >> 24,
      i >> 16 & 255,
      i >> 8 & 255,
      i & 255,
      s >> 24,
      s >> 16 & 255,
      s >> 8 & 255,
      s & 255,
      85,
      196,
      // 'und' language (undetermined)
      0,
      0
    ]));
  }
  static mdia(e) {
    return U.box(U.types.mdia, U.mdhd(e.timescale || 0, e.duration || 0), U.hdlr(e.type), U.minf(e));
  }
  static mfhd(e) {
    return U.box(U.types.mfhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // flags
      e >> 24,
      e >> 16 & 255,
      e >> 8 & 255,
      e & 255
      // sequence_number
    ]));
  }
  static minf(e) {
    return e.type === "audio" ? U.box(U.types.minf, U.box(U.types.smhd, U.SMHD), U.DINF, U.stbl(e)) : U.box(U.types.minf, U.box(U.types.vmhd, U.VMHD), U.DINF, U.stbl(e));
  }
  static moof(e, t, i) {
    return U.box(U.types.moof, U.mfhd(e), U.traf(i, t));
  }
  static moov(e) {
    let t = e.length;
    const i = [];
    for (; t--; )
      i[t] = U.trak(e[t]);
    return U.box.apply(null, [U.types.moov, U.mvhd(e[0].timescale || 0, e[0].duration || 0)].concat(i).concat(U.mvex(e)));
  }
  static mvex(e) {
    let t = e.length;
    const i = [];
    for (; t--; )
      i[t] = U.trex(e[t]);
    return U.box.apply(null, [U.types.mvex, ...i]);
  }
  static mvhd(e, t) {
    t *= e;
    const i = Math.floor(t / (ss + 1)), s = Math.floor(t % (ss + 1)), n = new Uint8Array([
      1,
      // version 1
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      2,
      // creation_time
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      3,
      // modification_time
      e >> 24 & 255,
      e >> 16 & 255,
      e >> 8 & 255,
      e & 255,
      // timescale
      i >> 24,
      i >> 16 & 255,
      i >> 8 & 255,
      i & 255,
      s >> 24,
      s >> 16 & 255,
      s >> 8 & 255,
      s & 255,
      0,
      1,
      0,
      0,
      // 1.0 rate
      1,
      0,
      // 1.0 volume
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      0,
      // reserved
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      64,
      0,
      0,
      0,
      // transformation: unity matrix
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // pre_defined
      255,
      255,
      255,
      255
      // next_track_ID
    ]);
    return U.box(U.types.mvhd, n);
  }
  static sdtp(e) {
    const t = e.samples || [], i = new Uint8Array(4 + t.length);
    let s, n;
    for (s = 0; s < t.length; s++)
      n = t[s].flags, i[s + 4] = n.dependsOn << 4 | n.isDependedOn << 2 | n.hasRedundancy;
    return U.box(U.types.sdtp, i);
  }
  static stbl(e) {
    return U.box(U.types.stbl, U.stsd(e), U.box(U.types.stts, U.STTS), U.box(U.types.stsc, U.STSC), U.box(U.types.stsz, U.STSZ), U.box(U.types.stco, U.STCO));
  }
  static avc1(e) {
    let t = [], i = [], s, n, a;
    for (s = 0; s < e.sps.length; s++)
      n = e.sps[s], a = n.byteLength, t.push(a >>> 8 & 255), t.push(a & 255), t = t.concat(Array.prototype.slice.call(n));
    for (s = 0; s < e.pps.length; s++)
      n = e.pps[s], a = n.byteLength, i.push(a >>> 8 & 255), i.push(a & 255), i = i.concat(Array.prototype.slice.call(n));
    const o = U.box(U.types.avcC, new Uint8Array([
      1,
      // version
      t[3],
      // profile
      t[4],
      // profile compat
      t[5],
      // level
      255,
      // lengthSizeMinusOne, hard-coded to 4 bytes
      224 | e.sps.length
      // 3bit reserved (111) + numOfSequenceParameterSets
    ].concat(t).concat([
      e.pps.length
      // numOfPictureParameterSets
    ]).concat(i))), c = e.width, l = e.height, d = e.pixelRatio[0], h = e.pixelRatio[1];
    return U.box(
      U.types.avc1,
      new Uint8Array([
        0,
        0,
        0,
        // reserved
        0,
        0,
        0,
        // reserved
        0,
        1,
        // data_reference_index
        0,
        0,
        // pre_defined
        0,
        0,
        // reserved
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // pre_defined
        c >> 8 & 255,
        c & 255,
        // width
        l >> 8 & 255,
        l & 255,
        // height
        0,
        72,
        0,
        0,
        // horizresolution
        0,
        72,
        0,
        0,
        // vertresolution
        0,
        0,
        0,
        0,
        // reserved
        0,
        1,
        // frame_count
        18,
        100,
        97,
        105,
        108,
        // dailymotion/hls.js
        121,
        109,
        111,
        116,
        105,
        111,
        110,
        47,
        104,
        108,
        115,
        46,
        106,
        115,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // compressorname
        0,
        24,
        // depth = 24
        17,
        17
      ]),
      // pre_defined = -1
      o,
      U.box(U.types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
      ])),
      // avgBitrate
      U.box(U.types.pasp, new Uint8Array([
        d >> 24,
        // hSpacing
        d >> 16 & 255,
        d >> 8 & 255,
        d & 255,
        h >> 24,
        // vSpacing
        h >> 16 & 255,
        h >> 8 & 255,
        h & 255
      ]))
    );
  }
  static esds(e) {
    const t = e.config;
    return new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      3,
      // descriptor_type
      25,
      // length
      0,
      1,
      // es_id
      0,
      // stream_priority
      4,
      // descriptor_type
      17,
      // length
      64,
      // codec : mpeg4_audio
      21,
      // stream_type
      0,
      0,
      0,
      // buffer_size
      0,
      0,
      0,
      0,
      // maxBitrate
      0,
      0,
      0,
      0,
      // avgBitrate
      5,
      // descriptor_type
      2,
      // length
      ...t,
      6,
      1,
      2
      // GASpecificConfig)); // length + audio config descriptor
    ]);
  }
  static audioStsd(e) {
    const t = e.samplerate || 0;
    return new Uint8Array([
      0,
      0,
      0,
      // reserved
      0,
      0,
      0,
      // reserved
      0,
      1,
      // data_reference_index
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // reserved
      0,
      e.channelCount || 0,
      // channelcount
      0,
      16,
      // sampleSize:16bits
      0,
      0,
      0,
      0,
      // reserved2
      t >> 8 & 255,
      t & 255,
      //
      0,
      0
    ]);
  }
  static mp4a(e) {
    return U.box(U.types.mp4a, U.audioStsd(e), U.box(U.types.esds, U.esds(e)));
  }
  static mp3(e) {
    return U.box(U.types[".mp3"], U.audioStsd(e));
  }
  static ac3(e) {
    return U.box(U.types["ac-3"], U.audioStsd(e), U.box(U.types.dac3, e.config));
  }
  static stsd(e) {
    const {
      segmentCodec: t
    } = e;
    if (e.type === "audio") {
      if (t === "aac")
        return U.box(U.types.stsd, U.STSD, U.mp4a(e));
      if (t === "ac3" && e.config)
        return U.box(U.types.stsd, U.STSD, U.ac3(e));
      if (t === "mp3" && e.codec === "mp3")
        return U.box(U.types.stsd, U.STSD, U.mp3(e));
    } else if (e.pps && e.sps) {
      if (t === "avc")
        return U.box(U.types.stsd, U.STSD, U.avc1(e));
      if (t === "hevc" && e.vps)
        return U.box(U.types.stsd, U.STSD, U.hvc1(e));
    } else
      throw new Error("video track missing pps or sps");
    throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`);
  }
  static tkhd(e) {
    const t = e.id, i = (e.duration || 0) * (e.timescale || 0), s = e.width || 0, n = e.height || 0, a = Math.floor(i / (ss + 1)), o = Math.floor(i % (ss + 1));
    return U.box(U.types.tkhd, new Uint8Array([
      1,
      // version 1
      0,
      0,
      7,
      // flags
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      2,
      // creation_time
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      3,
      // modification_time
      t >> 24 & 255,
      t >> 16 & 255,
      t >> 8 & 255,
      t & 255,
      // track_ID
      0,
      0,
      0,
      0,
      // reserved
      a >> 24,
      a >> 16 & 255,
      a >> 8 & 255,
      a & 255,
      o >> 24,
      o >> 16 & 255,
      o >> 8 & 255,
      o & 255,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // reserved
      0,
      0,
      // layer
      0,
      0,
      // alternate_group
      0,
      0,
      // non-audio track volume
      0,
      0,
      // reserved
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      64,
      0,
      0,
      0,
      // transformation: unity matrix
      s >> 8 & 255,
      s & 255,
      0,
      0,
      // width
      n >> 8 & 255,
      n & 255,
      0,
      0
      // height
    ]));
  }
  static traf(e, t) {
    const i = U.sdtp(e), s = e.id, n = Math.floor(t / (ss + 1)), a = Math.floor(t % (ss + 1));
    return U.box(
      U.types.traf,
      U.box(U.types.tfhd, new Uint8Array([
        0,
        // version 0
        0,
        0,
        0,
        // flags
        s >> 24,
        s >> 16 & 255,
        s >> 8 & 255,
        s & 255
        // track_ID
      ])),
      U.box(U.types.tfdt, new Uint8Array([
        1,
        // version 1
        0,
        0,
        0,
        // flags
        n >> 24,
        n >> 16 & 255,
        n >> 8 & 255,
        n & 255,
        a >> 24,
        a >> 16 & 255,
        a >> 8 & 255,
        a & 255
      ])),
      U.trun(e, i.length + 16 + // tfhd
      20 + // tfdt
      8 + // traf header
      16 + // mfhd
      8 + // moof header
      8),
      // mdat header
      i
    );
  }
  /**
   * Generate a track box.
   * @param track a track definition
   */
  static trak(e) {
    return e.duration = e.duration || 4294967295, U.box(U.types.trak, U.tkhd(e), U.mdia(e));
  }
  static trex(e) {
    const t = e.id;
    return U.box(U.types.trex, new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      t >> 24,
      t >> 16 & 255,
      t >> 8 & 255,
      t & 255,
      // track_ID
      0,
      0,
      0,
      1,
      // default_sample_description_index
      0,
      0,
      0,
      0,
      // default_sample_duration
      0,
      0,
      0,
      0,
      // default_sample_size
      0,
      1,
      0,
      1
      // default_sample_flags
    ]));
  }
  static trun(e, t) {
    const i = e.samples || [], s = i.length, n = 12 + 16 * s, a = new Uint8Array(n);
    let o, c, l, d, h, u;
    for (t += 8 + n, a.set([
      e.type === "video" ? 1 : 0,
      // version 1 for video with signed-int sample_composition_time_offset
      0,
      15,
      1,
      // flags
      s >>> 24 & 255,
      s >>> 16 & 255,
      s >>> 8 & 255,
      s & 255,
      // sample_count
      t >>> 24 & 255,
      t >>> 16 & 255,
      t >>> 8 & 255,
      t & 255
      // data_offset
    ], 0), o = 0; o < s; o++)
      c = i[o], l = c.duration, d = c.size, h = c.flags, u = c.cts, a.set([
        l >>> 24 & 255,
        l >>> 16 & 255,
        l >>> 8 & 255,
        l & 255,
        // sample_duration
        d >>> 24 & 255,
        d >>> 16 & 255,
        d >>> 8 & 255,
        d & 255,
        // sample_size
        h.isLeading << 2 | h.dependsOn,
        h.isDependedOn << 6 | h.hasRedundancy << 4 | h.paddingValue << 1 | h.isNonSync,
        h.degradPrio & 61440,
        h.degradPrio & 15,
        // sample_flags
        u >>> 24 & 255,
        u >>> 16 & 255,
        u >>> 8 & 255,
        u & 255
        // sample_composition_time_offset
      ], 12 + 16 * o);
    return U.box(U.types.trun, a);
  }
  static initSegment(e) {
    U.types || U.init();
    const t = U.moov(e);
    return Qt(U.FTYP, t);
  }
  static hvc1(e) {
    const t = e.params, i = [e.vps, e.sps, e.pps], s = 4, n = new Uint8Array([1, t.general_profile_space << 6 | (t.general_tier_flag ? 32 : 0) | t.general_profile_idc, t.general_profile_compatibility_flags[0], t.general_profile_compatibility_flags[1], t.general_profile_compatibility_flags[2], t.general_profile_compatibility_flags[3], t.general_constraint_indicator_flags[0], t.general_constraint_indicator_flags[1], t.general_constraint_indicator_flags[2], t.general_constraint_indicator_flags[3], t.general_constraint_indicator_flags[4], t.general_constraint_indicator_flags[5], t.general_level_idc, 240 | t.min_spatial_segmentation_idc >> 8, 255 & t.min_spatial_segmentation_idc, 252 | t.parallelismType, 252 | t.chroma_format_idc, 248 | t.bit_depth_luma_minus8, 248 | t.bit_depth_chroma_minus8, 0, parseInt(t.frame_rate.fps), s - 1 | t.temporal_id_nested << 2 | t.num_temporal_layers << 3 | (t.frame_rate.fixed ? 64 : 0), i.length]);
    let a = n.length;
    for (let p = 0; p < i.length; p += 1) {
      a += 3;
      for (let m = 0; m < i[p].length; m += 1)
        a += 2 + i[p][m].length;
    }
    const o = new Uint8Array(a);
    o.set(n, 0), a = n.length;
    const c = i.length - 1;
    for (let p = 0; p < i.length; p += 1) {
      o.set(new Uint8Array([32 + p | (p === c ? 128 : 0), 0, i[p].length]), a), a += 3;
      for (let m = 0; m < i[p].length; m += 1)
        o.set(new Uint8Array([i[p][m].length >> 8, i[p][m].length & 255]), a), a += 2, o.set(i[p][m], a), a += i[p][m].length;
    }
    const l = U.box(U.types.hvcC, o), d = e.width, h = e.height, u = e.pixelRatio[0], f = e.pixelRatio[1];
    return U.box(
      U.types.hvc1,
      new Uint8Array([
        0,
        0,
        0,
        // reserved
        0,
        0,
        0,
        // reserved
        0,
        1,
        // data_reference_index
        0,
        0,
        // pre_defined
        0,
        0,
        // reserved
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // pre_defined
        d >> 8 & 255,
        d & 255,
        // width
        h >> 8 & 255,
        h & 255,
        // height
        0,
        72,
        0,
        0,
        // horizresolution
        0,
        72,
        0,
        0,
        // vertresolution
        0,
        0,
        0,
        0,
        // reserved
        0,
        1,
        // frame_count
        18,
        100,
        97,
        105,
        108,
        // dailymotion/hls.js
        121,
        109,
        111,
        116,
        105,
        111,
        110,
        47,
        104,
        108,
        115,
        46,
        106,
        115,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        // compressorname
        0,
        24,
        // depth = 24
        17,
        17
      ]),
      // pre_defined = -1
      l,
      U.box(U.types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
      ])),
      // avgBitrate
      U.box(U.types.pasp, new Uint8Array([
        u >> 24,
        // hSpacing
        u >> 16 & 255,
        u >> 8 & 255,
        u & 255,
        f >> 24,
        // vSpacing
        f >> 16 & 255,
        f >> 8 & 255,
        f & 255
      ]))
    );
  }
}
U.types = void 0;
U.HDLR_TYPES = void 0;
U.STTS = void 0;
U.STSC = void 0;
U.STCO = void 0;
U.STSZ = void 0;
U.VMHD = void 0;
U.SMHD = void 0;
U.STSD = void 0;
U.FTYP = void 0;
U.DINF = void 0;
const M_ = 9e4;
function th(r, e, t = 1, i = !1) {
  const s = r * e * t;
  return i ? Math.round(s) : s;
}
function z8(r, e, t = 1, i = !1) {
  return th(r, e, 1 / t, i);
}
function Kr(r, e = !1) {
  return th(r, 1e3, 1 / M_, e);
}
function j8(r, e = 1) {
  return th(r, M_, 1 / e);
}
const Q8 = 10 * 1e3, J8 = 1024, q8 = 1152, eR = 1536;
let rr = null, C0 = null;
function wp(r, e, t, i) {
  return {
    duration: e,
    size: t,
    cts: i,
    flags: {
      isLeading: 0,
      isDependedOn: 0,
      hasRedundancy: 0,
      degradPrio: 0,
      dependsOn: r ? 2 : 1,
      isNonSync: r ? 0 : 1
    }
  };
}
class ka extends qt {
  constructor(e, t, i, s) {
    if (super("mp4-remuxer", s), this.observer = void 0, this.config = void 0, this.typeSupported = void 0, this.ISGenerated = !1, this._initPTS = null, this._initDTS = null, this.nextVideoTs = null, this.nextAudioTs = null, this.videoSampleDuration = null, this.isAudioContiguous = !1, this.isVideoContiguous = !1, this.videoTrackConfig = void 0, this.observer = e, this.config = t, this.typeSupported = i, this.ISGenerated = !1, rr === null) {
      const a = (navigator.userAgent || "").match(/Chrome\/(\d+)/i);
      rr = a ? parseInt(a[1]) : 0;
    }
    if (C0 === null) {
      const n = navigator.userAgent.match(/Safari\/(\d+)/i);
      C0 = n ? parseInt(n[1]) : 0;
    }
  }
  destroy() {
    this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  }
  resetTimeStamp(e) {
    this.log("initPTS & initDTS reset"), this._initPTS = this._initDTS = e;
  }
  resetNextTimestamp() {
    this.log("reset next timestamp"), this.isVideoContiguous = !1, this.isAudioContiguous = !1;
  }
  resetInitSegment() {
    this.log("ISGenerated flag reset"), this.ISGenerated = !1, this.videoTrackConfig = void 0;
  }
  getVideoStartPts(e) {
    let t = !1;
    const i = e[0].pts, s = e.reduce((n, a) => {
      let o = a.pts, c = o - n;
      return c < -4294967296 && (t = !0, o = Yt(o, i), c = o - n), c > 0 ? n : o;
    }, i);
    return t && this.debug("PTS rollover detected"), s;
  }
  remux(e, t, i, s, n, a, o, c) {
    let l, d, h, u, f, p, m = n, g = n;
    const x = e.pid > -1, _ = t.pid > -1, v = t.samples.length, E = e.samples.length > 0, b = o && v > 0 || v > 1;
    if ((!x || E) && (!_ || b) || this.ISGenerated || o) {
      if (this.ISGenerated) {
        var C, I, L, R;
        const N = this.videoTrackConfig;
        (N && (t.width !== N.width || t.height !== N.height || ((C = t.pixelRatio) == null ? void 0 : C[0]) !== ((I = N.pixelRatio) == null ? void 0 : I[0]) || ((L = t.pixelRatio) == null ? void 0 : L[1]) !== ((R = N.pixelRatio) == null ? void 0 : R[1])) || !N && b || this.nextAudioTs === null && E) && this.resetInitSegment();
      }
      this.ISGenerated || (h = this.generateIS(e, t, n, a));
      const D = this.isVideoContiguous;
      let M = -1, w;
      if (b && (M = tR(t.samples), !D && this.config.forceKeyFrameOnDiscontinuity))
        if (p = !0, M > 0) {
          this.warn(`Dropped ${M} out of ${v} video samples due to a missing keyframe`);
          const N = this.getVideoStartPts(t.samples);
          t.samples = t.samples.slice(M), t.dropped += M, g += (t.samples[0].pts - N) / t.inputTimeScale, w = g;
        } else M === -1 && (this.warn(`No keyframe found out of ${v} video samples`), p = !1);
      if (this.ISGenerated) {
        if (E && b) {
          const N = this.getVideoStartPts(t.samples), G = (Yt(e.samples[0].pts, N) - N) / t.inputTimeScale;
          m += Math.max(0, G), g += Math.max(0, -G);
        }
        if (E) {
          if (e.samplerate || (this.warn("regenerate InitSegment as audio detected"), h = this.generateIS(e, t, n, a)), d = this.remuxAudio(e, m, this.isAudioContiguous, a, _ || b || c === te.AUDIO ? g : void 0), b) {
            const N = d ? d.endPTS - d.startPTS : 0;
            t.inputTimeScale || (this.warn("regenerate InitSegment as video detected"), h = this.generateIS(e, t, n, a)), l = this.remuxVideo(t, g, D, N);
          }
        } else b && (l = this.remuxVideo(t, g, D, 0));
        l && (l.firstKeyFrame = M, l.independent = M !== -1, l.firstKeyFramePTS = w);
      }
    }
    return this.ISGenerated && this._initPTS && this._initDTS && (i.samples.length && (f = B_(i, n, this._initPTS, this._initDTS)), s.samples.length && (u = F_(s, n, this._initPTS))), {
      audio: d,
      video: l,
      initSegment: h,
      independent: p,
      text: u,
      id3: f
    };
  }
  generateIS(e, t, i, s) {
    const n = e.samples, a = t.samples, o = this.typeSupported, c = {}, l = this._initPTS;
    let d = !l || s, h = "audio/mp4", u, f, p, m = -1;
    if (d && (u = f = 1 / 0), e.config && n.length) {
      switch (e.timescale = e.samplerate, e.segmentCodec) {
        case "mp3":
          o.mpeg ? (h = "audio/mpeg", e.codec = "") : o.mp3 && (e.codec = "mp3");
          break;
        case "ac3":
          e.codec = "ac-3";
          break;
      }
      c.audio = {
        id: "audio",
        container: h,
        codec: e.codec,
        initSegment: e.segmentCodec === "mp3" && o.mpeg ? new Uint8Array(0) : U.initSegment([e]),
        metadata: {
          channelCount: e.channelCount
        }
      }, d && (m = e.id, p = e.inputTimeScale, !l || p !== l.timescale ? u = f = n[0].pts - Math.round(p * i) : d = !1);
    }
    if (t.sps && t.pps && a.length) {
      if (t.timescale = t.inputTimeScale, c.video = {
        id: "main",
        container: "video/mp4",
        codec: t.codec,
        initSegment: U.initSegment([t]),
        metadata: {
          width: t.width,
          height: t.height
        }
      }, d)
        if (m = t.id, p = t.inputTimeScale, !l || p !== l.timescale) {
          const g = this.getVideoStartPts(a), x = Math.round(p * i);
          f = Math.min(f, Yt(a[0].dts, g) - x), u = Math.min(u, g - x);
        } else
          d = !1;
      this.videoTrackConfig = {
        width: t.width,
        height: t.height,
        pixelRatio: t.pixelRatio
      };
    }
    if (Object.keys(c).length)
      return this.ISGenerated = !0, d ? (l && this.warn(`Timestamps at playlist time: ${s ? "" : "~"}${i} ${u / p} != initPTS: ${l.baseTime / l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`), this.log(`Found initPTS at playlist time: ${i} offset: ${u / p} (${u}/${p}) trackId: ${m}`), this._initPTS = {
        baseTime: u,
        timescale: p,
        trackId: m
      }, this._initDTS = {
        baseTime: f,
        timescale: p,
        trackId: m
      }) : u = p = void 0, {
        tracks: c,
        initPTS: u,
        timescale: p,
        trackId: m
      };
  }
  remuxVideo(e, t, i, s) {
    const n = e.inputTimeScale, a = e.samples, o = [], c = a.length, l = this._initPTS, d = l.baseTime * n / l.timescale;
    let h = this.nextVideoTs, u = 8, f = this.videoSampleDuration, p, m, g = Number.POSITIVE_INFINITY, x = Number.NEGATIVE_INFINITY, _ = !1;
    if (!i || h === null) {
      const k = d + t * n, P = a[0].pts - Yt(a[0].dts, a[0].pts);
      rr && h !== null && Math.abs(k - P - (h + d)) < 15e3 ? i = !0 : h = k - P - d;
    }
    const v = h + d;
    for (let k = 0; k < c; k++) {
      const P = a[k];
      P.pts = Yt(P.pts, v), P.dts = Yt(P.dts, v), P.dts < a[k > 0 ? k - 1 : k].dts && (_ = !0);
    }
    _ && a.sort(function(k, P) {
      const B = k.dts - P.dts, O = k.pts - P.pts;
      return B || O;
    }), p = a[0].dts, m = a[a.length - 1].dts;
    const E = m - p, b = E ? Math.round(E / (c - 1)) : f || e.inputTimeScale / 30;
    if (i) {
      const k = p - v, P = k > b, B = k < -1;
      if ((P || B) && (P ? this.warn(`${(e.segmentCodec || "").toUpperCase()}: ${Kr(k, !0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`) : this.warn(`${(e.segmentCodec || "").toUpperCase()}: ${Kr(-k, !0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`), !B || v >= a[0].pts || rr)) {
        p = v;
        const O = a[0].pts - k;
        if (P)
          a[0].dts = p, a[0].pts = O;
        else {
          let j = !0;
          for (let Q = 0; Q < a.length && !(a[Q].dts > O && j); Q++) {
            const ne = a[Q].pts;
            if (a[Q].dts -= k, a[Q].pts -= k, Q < a.length - 1) {
              const J = a[Q + 1].pts, Se = a[Q].pts, Ce = J <= Se, Te = J <= ne;
              j = Ce == Te;
            }
          }
        }
        this.log(`Video: Initial PTS/DTS adjusted: ${Kr(O, !0)}/${Kr(p, !0)}, delta: ${Kr(k, !0)} ms`);
      }
    }
    p = Math.max(0, p);
    let A = 0, C = 0, I = p;
    for (let k = 0; k < c; k++) {
      const P = a[k], B = P.units, O = B.length;
      let j = 0;
      for (let Q = 0; Q < O; Q++)
        j += B[Q].data.length;
      C += j, A += O, P.length = j, P.dts < I ? (P.dts = I, I += b / 4 | 0 || 1) : I = P.dts, g = Math.min(P.pts, g), x = Math.max(P.pts, x);
    }
    m = a[c - 1].dts;
    const L = C + 4 * A + 8;
    let R;
    try {
      R = new Uint8Array(L);
    } catch (k) {
      this.observer.emit(T.ERROR, T.ERROR, {
        type: ie.MUX_ERROR,
        details: V.REMUX_ALLOC_ERROR,
        fatal: !1,
        error: k,
        bytes: L,
        reason: `fail allocating video mdat ${L}`
      });
      return;
    }
    const D = new DataView(R.buffer);
    D.setUint32(0, L), R.set(U.types.mdat, 4);
    let M = !1, w = Number.POSITIVE_INFINITY, N = Number.POSITIVE_INFINITY, H = Number.NEGATIVE_INFINITY, G = Number.NEGATIVE_INFINITY;
    for (let k = 0; k < c; k++) {
      const P = a[k], B = P.units;
      let O = 0;
      for (let ne = 0, J = B.length; ne < J; ne++) {
        const Se = B[ne], Ce = Se.data, Te = Se.data.byteLength;
        D.setUint32(u, Te), u += 4, R.set(Ce, u), u += Te, O += 4 + Te;
      }
      let j;
      if (k < c - 1)
        f = a[k + 1].dts - P.dts, j = a[k + 1].pts - P.pts;
      else {
        const ne = this.config, J = k > 0 ? P.dts - a[k - 1].dts : b;
        if (j = k > 0 ? P.pts - a[k - 1].pts : b, ne.stretchShortVideoTrack && this.nextAudioTs !== null) {
          const Se = Math.floor(ne.maxBufferHole * n), Ce = (s ? g + s * n : this.nextAudioTs + d) - P.pts;
          Ce > Se ? (f = Ce - J, f < 0 ? f = J : M = !0, this.log(`It is approximately ${Ce / 90} ms to the next segment; using duration ${f / 90} ms for the last video frame.`)) : f = J;
        } else
          f = J;
      }
      const Q = Math.round(P.pts - P.dts);
      w = Math.min(w, f), H = Math.max(H, f), N = Math.min(N, j), G = Math.max(G, j), o.push(wp(P.key, f, O, Q));
    }
    if (o.length) {
      if (rr) {
        if (rr < 70) {
          const k = o[0].flags;
          k.dependsOn = 2, k.isNonSync = 0;
        }
      } else if (C0 && G - N < H - w && b / H < 0.025 && o[0].cts === 0) {
        this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");
        let k = p;
        for (let P = 0, B = o.length; P < B; P++) {
          const O = k + o[P].duration, j = k + o[P].cts;
          if (P < B - 1) {
            const Q = O + o[P + 1].cts;
            o[P].duration = Q - j;
          } else
            o[P].duration = P ? o[P - 1].duration : b;
          o[P].cts = 0, k = O;
        }
      }
    }
    f = M || !f ? b : f;
    const Z = m + f;
    this.nextVideoTs = h = Z - d, this.videoSampleDuration = f, this.isVideoContiguous = !0;
    const W = {
      data1: U.moof(e.sequenceNumber++, p, Me(e, {
        samples: o
      })),
      data2: R,
      startPTS: (g - d) / n,
      endPTS: (x + f - d) / n,
      startDTS: (p - d) / n,
      endDTS: h / n,
      type: "video",
      hasAudio: !1,
      hasVideo: !0,
      nb: o.length,
      dropped: e.dropped
    };
    return e.samples = [], e.dropped = 0, W;
  }
  getSamplesPerFrame(e) {
    switch (e.segmentCodec) {
      case "mp3":
        return q8;
      case "ac3":
        return eR;
      default:
        return J8;
    }
  }
  remuxAudio(e, t, i, s, n) {
    const a = e.inputTimeScale, o = e.samplerate ? e.samplerate : a, c = a / o, l = this.getSamplesPerFrame(e), d = l * c, h = this._initPTS, u = e.segmentCodec === "mp3" && this.typeSupported.mpeg, f = [], p = n !== void 0;
    let m = e.samples, g = u ? 0 : 8, x = this.nextAudioTs || -1;
    const _ = h.baseTime * a / h.timescale, v = _ + t * a;
    if (this.isAudioContiguous = i = i || m.length && x > 0 && (s && Math.abs(v - (x + _)) < 9e3 || Math.abs(Yt(m[0].pts, v) - (x + _)) < 20 * d), m.forEach(function(G) {
      G.pts = Yt(G.pts, v);
    }), !i || x < 0) {
      if (m = m.filter((G) => G.pts >= 0), !m.length)
        return;
      n === 0 ? x = 0 : s && !p ? x = Math.max(0, v - _) : x = m[0].pts - _;
    }
    if (e.segmentCodec === "aac") {
      const G = this.config.maxAudioFramesDrift;
      for (let Z = 0, $ = x + _; Z < m.length; Z++) {
        const Y = m[Z], W = Y.pts, k = W - $, P = Math.abs(1e3 * k / a);
        if (k <= -G * d && p)
          Z === 0 && (this.warn(`Audio frame @ ${(W / a).toFixed(3)}s overlaps marker by ${Math.round(1e3 * k / a)} ms.`), this.nextAudioTs = x = W - _, $ = W);
        else if (k >= G * d && P < Q8 && p) {
          let B = Math.round(k / d);
          for ($ = W - B * d; $ < 0 && B && d; )
            B--, $ += d;
          Z === 0 && (this.nextAudioTs = x = $ - _), this.warn(`Injecting ${B} audio frames @ ${(($ - _) / a).toFixed(3)}s due to ${Math.round(1e3 * k / a)} ms gap.`);
          for (let O = 0; O < B; O++) {
            let j = Y8.getSilentFrame(e.parsedCodec || e.manifestCodec || e.codec, e.channelCount);
            j || (this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."), j = Y.unit.subarray()), m.splice(Z, 0, {
              unit: j,
              pts: $
            }), $ += d, Z++;
          }
        }
        Y.pts = $, $ += d;
      }
    }
    let E = null, b = null, A, C = 0, I = m.length;
    for (; I--; )
      C += m[I].unit.byteLength;
    for (let G = 0, Z = m.length; G < Z; G++) {
      const $ = m[G], Y = $.unit;
      let W = $.pts;
      if (b !== null) {
        const P = f[G - 1];
        P.duration = Math.round((W - b) / c);
      } else if (i && e.segmentCodec === "aac" && (W = x + _), E = W, C > 0) {
        C += g;
        try {
          A = new Uint8Array(C);
        } catch (P) {
          this.observer.emit(T.ERROR, T.ERROR, {
            type: ie.MUX_ERROR,
            details: V.REMUX_ALLOC_ERROR,
            fatal: !1,
            error: P,
            bytes: C,
            reason: `fail allocating audio mdat ${C}`
          });
          return;
        }
        u || (new DataView(A.buffer).setUint32(0, C), A.set(U.types.mdat, 4));
      } else
        return;
      A.set(Y, g);
      const k = Y.byteLength;
      g += k, f.push(wp(!0, l, k, 0)), b = W;
    }
    const L = f.length;
    if (!L)
      return;
    const R = f[f.length - 1];
    x = b - _, this.nextAudioTs = x + c * R.duration;
    const D = u ? new Uint8Array(0) : U.moof(e.sequenceNumber++, E / c, Me({}, e, {
      samples: f
    }));
    e.samples = [];
    const M = (E - _) / a, w = x / a, H = {
      data1: D,
      data2: A,
      startPTS: M,
      endPTS: w,
      startDTS: M,
      endDTS: w,
      type: "audio",
      hasAudio: !0,
      hasVideo: !1,
      nb: L
    };
    return this.isAudioContiguous = !0, H;
  }
}
function Yt(r, e) {
  let t;
  if (e === null)
    return r;
  for (e < r ? t = -8589934592 : t = 8589934592; Math.abs(r - e) > 4294967296; )
    r += t;
  return r;
}
function tR(r) {
  for (let e = 0; e < r.length; e++)
    if (r[e].key)
      return e;
  return -1;
}
function B_(r, e, t, i) {
  const s = r.samples.length;
  if (!s)
    return;
  const n = r.inputTimeScale;
  for (let o = 0; o < s; o++) {
    const c = r.samples[o];
    c.pts = Yt(c.pts - t.baseTime * n / t.timescale, e * n) / n, c.dts = Yt(c.dts - i.baseTime * n / i.timescale, e * n) / n;
  }
  const a = r.samples;
  return r.samples = [], {
    samples: a
  };
}
function F_(r, e, t) {
  const i = r.samples.length;
  if (!i)
    return;
  const s = r.inputTimeScale;
  for (let a = 0; a < i; a++) {
    const o = r.samples[a];
    o.pts = Yt(o.pts - t.baseTime * s / t.timescale, e * s) / s;
  }
  r.samples.sort((a, o) => a.pts - o.pts);
  const n = r.samples;
  return r.samples = [], {
    samples: n
  };
}
class iR extends qt {
  constructor(e, t, i, s) {
    super("passthrough-remuxer", s), this.emitInitSegment = !1, this.audioCodec = void 0, this.videoCodec = void 0, this.initData = void 0, this.initPTS = null, this.initTracks = void 0, this.lastEndTime = null, this.isVideoContiguous = !1;
  }
  destroy() {
  }
  resetTimeStamp(e) {
    this.lastEndTime = null;
    const t = this.initPTS;
    t && e && t.baseTime === e.baseTime && t.timescale === e.timescale || (this.initPTS = e);
  }
  resetNextTimestamp() {
    this.isVideoContiguous = !1, this.lastEndTime = null;
  }
  resetInitSegment(e, t, i, s) {
    this.audioCodec = t, this.videoCodec = i, this.generateInitSegment(e, s), this.emitInitSegment = !0;
  }
  generateInitSegment(e, t) {
    let {
      audioCodec: i,
      videoCodec: s
    } = this;
    if (!(e != null && e.byteLength)) {
      this.initTracks = void 0, this.initData = void 0;
      return;
    }
    const {
      audio: n,
      video: a
    } = this.initData = Xg(e);
    if (t)
      Z4(e, t);
    else {
      const c = n || a;
      c != null && c.encrypted && this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`);
    }
    n && (i = Mp(n, Oe.AUDIO, this)), a && (s = Mp(a, Oe.VIDEO, this));
    const o = {};
    n && a ? o.audiovideo = {
      container: "video/mp4",
      codec: i + "," + s,
      supplemental: a.supplemental,
      encrypted: a.encrypted,
      initSegment: e,
      id: "main"
    } : n ? o.audio = {
      container: "audio/mp4",
      codec: i,
      encrypted: n.encrypted,
      initSegment: e,
      id: "audio"
    } : a ? o.video = {
      container: "video/mp4",
      codec: s,
      supplemental: a.supplemental,
      encrypted: a.encrypted,
      initSegment: e,
      id: "main"
    } : this.warn("initSegment does not contain moov or trak boxes."), this.initTracks = o;
  }
  remux(e, t, i, s, n, a) {
    var o, c;
    let {
      initPTS: l,
      lastEndTime: d
    } = this;
    const h = {
      audio: void 0,
      video: void 0,
      text: s,
      id3: i,
      initSegment: void 0
    };
    q(d) || (d = this.lastEndTime = n || 0);
    const u = t.samples;
    if (!u.length)
      return h;
    const f = {
      initPTS: void 0,
      timescale: void 0,
      trackId: void 0
    };
    let p = this.initData;
    if ((o = p) != null && o.length || (this.generateInitSegment(u), p = this.initData), !((c = p) != null && c.length))
      return this.warn("Failed to generate initSegment."), h;
    this.emitInitSegment && (f.tracks = this.initTracks, this.emitInitSegment = !1);
    const m = $4(u, p, this), g = p.audio ? m[p.audio.id] : null, x = p.video ? m[p.video.id] : null, _ = ia(x, 1 / 0), v = ia(g, 1 / 0), E = ia(x, 0, !0), b = ia(g, 0, !0);
    let A = n, C = 0;
    const I = g && (!x || !l && v < _ || l && l.trackId === p.audio.id), L = I ? g : x;
    if (L) {
      const $ = L.timescale, Y = L.start - n * $, W = I ? p.audio.id : p.video.id;
      A = L.start / $, C = I ? b - v : E - _, (a || !l) && (sR(l, A, n, C) || $ !== l.timescale) && (l && this.warn(`Timestamps at playlist time: ${a ? "" : "~"}${n} ${Y / $} != initPTS: ${l.baseTime / l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`), this.log(`Found initPTS at playlist time: ${n} offset: ${A - n} (${Y}/${$}) trackId: ${W}`), l = null, f.initPTS = Y, f.timescale = $, f.trackId = W);
    } else
      this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);
    l ? (f.initPTS = l.baseTime, f.timescale = l.timescale, f.trackId = l.trackId) : ((!f.timescale || f.trackId === void 0 || f.initPTS === void 0) && (this.warn("Could not set initPTS"), f.initPTS = A, f.timescale = 1, f.trackId = -1), this.initPTS = l = {
      baseTime: f.initPTS,
      timescale: f.timescale,
      trackId: f.trackId
    });
    const R = A - l.baseTime / l.timescale, D = R + C;
    C > 0 ? this.lastEndTime = D : (this.warn("Duration parsed from mp4 should be greater than zero"), this.resetNextTimestamp());
    const M = !!p.audio, w = !!p.video;
    let N = "";
    M && (N += "audio"), w && (N += "video");
    const H = (p.audio ? p.audio.encrypted : !1) || (p.video ? p.video.encrypted : !1), G = {
      data1: u,
      startPTS: R,
      startDTS: R,
      endPTS: D,
      endDTS: D,
      type: N,
      hasAudio: M,
      hasVideo: w,
      nb: 1,
      dropped: 0,
      encrypted: H
    };
    h.audio = M && !w ? G : void 0, h.video = w ? G : void 0;
    const Z = x == null ? void 0 : x.sampleCount;
    if (Z) {
      const $ = x.keyFrameIndex, Y = $ !== -1;
      G.nb = Z, G.dropped = $ === 0 || this.isVideoContiguous ? 0 : Y ? $ : Z, G.independent = Y, G.firstKeyFrame = $, Y && x.keyFrameStart && (G.firstKeyFramePTS = (x.keyFrameStart - l.baseTime) / l.timescale), this.isVideoContiguous || (h.independent = Y), this.isVideoContiguous || (this.isVideoContiguous = Y), G.dropped && this.warn(`fmp4 does not start with IDR: firstIDR ${$}/${Z} dropped: ${G.dropped} start: ${G.firstKeyFramePTS || "NA"}`);
    }
    return h.initSegment = f, h.id3 = B_(i, n, l, l), s.samples.length && (h.text = F_(s, n, l)), h;
  }
}
function ia(r, e, t = !1) {
  return (r == null ? void 0 : r.start) !== void 0 ? (r.start + (t ? r.duration : 0)) / r.timescale : e;
}
function sR(r, e, t, i) {
  if (r === null)
    return !0;
  const s = Math.max(i, 1), n = e - r.baseTime / r.timescale;
  return Math.abs(n - t) > s;
}
function Mp(r, e, t) {
  const i = r.codec;
  return i && i.length > 4 ? i : e === Oe.AUDIO ? i === "ec-3" || i === "ac-3" || i === "alac" ? i : i === "fLaC" || i === "Opus" ? to(i, !1) : (t.warn(`Unhandled audio codec "${i}" in mp4 MAP`), i || "mp4a") : (t.warn(`Unhandled video codec "${i}" in mp4 MAP`), i || "avc1");
}
let $i;
try {
  $i = self.performance.now.bind(self.performance);
} catch {
  $i = Date.now;
}
const wa = [{
  demux: W8,
  remux: iR
}, {
  demux: os,
  remux: ka
}, {
  demux: N8,
  remux: ka
}, {
  demux: U8,
  remux: ka
}];
wa.splice(2, 0, {
  demux: G8,
  remux: ka
});
class Bp {
  constructor(e, t, i, s, n, a) {
    this.asyncResult = !1, this.logger = void 0, this.observer = void 0, this.typeSupported = void 0, this.config = void 0, this.id = void 0, this.demuxer = void 0, this.remuxer = void 0, this.decrypter = void 0, this.probe = void 0, this.decryptionPromise = null, this.transmuxConfig = void 0, this.currentTransmuxState = void 0, this.observer = e, this.typeSupported = t, this.config = i, this.id = n, this.logger = a;
  }
  configure(e) {
    this.transmuxConfig = e, this.decrypter && this.decrypter.reset();
  }
  push(e, t, i, s) {
    const n = i.transmuxing;
    n.executeStart = $i();
    let a = new Uint8Array(e);
    const {
      currentTransmuxState: o,
      transmuxConfig: c
    } = this;
    s && (this.currentTransmuxState = s);
    const {
      contiguous: l,
      discontinuity: d,
      trackSwitch: h,
      accurateTimeOffset: u,
      timeOffset: f,
      initSegmentChange: p
    } = s || o, {
      audioCodec: m,
      videoCodec: g,
      defaultInitPts: x,
      duration: _,
      initSegmentData: v
    } = c, E = rR(a, t);
    if (E && br(E.method)) {
      const I = this.getDecrypter(), L = Kd(E.method);
      if (I.isSync()) {
        let R = I.softwareDecrypt(a, E.key.buffer, E.iv.buffer, L);
        if (i.part > -1) {
          const M = I.flush();
          R = M && M.buffer;
        }
        if (!R)
          return n.executeEnd = $i(), R0(i);
        a = new Uint8Array(R);
      } else
        return this.asyncResult = !0, this.decryptionPromise = I.webCryptoDecrypt(a, E.key.buffer, E.iv.buffer, L).then((R) => {
          const D = this.push(R, null, i);
          return this.decryptionPromise = null, D;
        }), this.decryptionPromise;
    }
    const b = this.needsProbing(d, h);
    if (b) {
      const I = this.configureTransmuxer(a);
      if (I)
        return this.logger.warn(`[transmuxer] ${I.message}`), this.observer.emit(T.ERROR, T.ERROR, {
          type: ie.MEDIA_ERROR,
          details: V.FRAG_PARSING_ERROR,
          fatal: !1,
          error: I,
          reason: I.message
        }), n.executeEnd = $i(), R0(i);
    }
    (d || h || p || b) && this.resetInitSegment(v, m, g, _, t), (d || p || b) && this.resetInitialTimestamp(x), l || this.resetContiguity();
    const A = this.transmux(a, E, f, u, i);
    this.asyncResult = bn(A);
    const C = this.currentTransmuxState;
    return C.contiguous = !0, C.discontinuity = !1, C.trackSwitch = !1, n.executeEnd = $i(), A;
  }
  // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  flush(e) {
    const t = e.transmuxing;
    t.executeStart = $i();
    const {
      decrypter: i,
      currentTransmuxState: s,
      decryptionPromise: n
    } = this;
    if (n)
      return this.asyncResult = !0, n.then(() => this.flush(e));
    const a = [], {
      timeOffset: o
    } = s;
    if (i) {
      const h = i.flush();
      h && a.push(this.push(h.buffer, null, e));
    }
    const {
      demuxer: c,
      remuxer: l
    } = this;
    if (!c || !l) {
      t.executeEnd = $i();
      const h = [R0(e)];
      return this.asyncResult ? Promise.resolve(h) : h;
    }
    const d = c.flush(o);
    return bn(d) ? (this.asyncResult = !0, d.then((h) => (this.flushRemux(a, h, e), a))) : (this.flushRemux(a, d, e), this.asyncResult ? Promise.resolve(a) : a);
  }
  flushRemux(e, t, i) {
    const {
      audioTrack: s,
      videoTrack: n,
      id3Track: a,
      textTrack: o
    } = t, {
      accurateTimeOffset: c,
      timeOffset: l
    } = this.currentTransmuxState;
    this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part > -1 ? " part: " + i.part : ""} of ${this.id === te.MAIN ? "level" : "track"} ${i.level}`);
    const d = this.remuxer.remux(s, n, a, o, l, c, !0, this.id);
    e.push({
      remuxResult: d,
      chunkMeta: i
    }), i.transmuxing.executeEnd = $i();
  }
  resetInitialTimestamp(e) {
    const {
      demuxer: t,
      remuxer: i
    } = this;
    !t || !i || (t.resetTimeStamp(e), i.resetTimeStamp(e));
  }
  resetContiguity() {
    const {
      demuxer: e,
      remuxer: t
    } = this;
    !e || !t || (e.resetContiguity(), t.resetNextTimestamp());
  }
  resetInitSegment(e, t, i, s, n) {
    const {
      demuxer: a,
      remuxer: o
    } = this;
    !a || !o || (a.resetInitSegment(e, t, i, s), o.resetInitSegment(e, t, i, n));
  }
  destroy() {
    this.demuxer && (this.demuxer.destroy(), this.demuxer = void 0), this.remuxer && (this.remuxer.destroy(), this.remuxer = void 0);
  }
  transmux(e, t, i, s, n) {
    let a;
    return t && t.method === "SAMPLE-AES" ? a = this.transmuxSampleAes(e, t, i, s, n) : a = this.transmuxUnencrypted(e, i, s, n), a;
  }
  transmuxUnencrypted(e, t, i, s) {
    const {
      audioTrack: n,
      videoTrack: a,
      id3Track: o,
      textTrack: c
    } = this.demuxer.demux(e, t, !1, !this.config.progressive);
    return {
      remuxResult: this.remuxer.remux(n, a, o, c, t, i, !1, this.id),
      chunkMeta: s
    };
  }
  transmuxSampleAes(e, t, i, s, n) {
    return this.demuxer.demuxSampleAes(e, t, i).then((a) => ({
      remuxResult: this.remuxer.remux(a.audioTrack, a.videoTrack, a.id3Track, a.textTrack, i, s, !1, this.id),
      chunkMeta: n
    }));
  }
  configureTransmuxer(e) {
    const {
      config: t,
      observer: i,
      typeSupported: s
    } = this;
    let n;
    for (let h = 0, u = wa.length; h < u; h++) {
      var a;
      if ((a = wa[h].demux) != null && a.probe(e, this.logger)) {
        n = wa[h];
        break;
      }
    }
    if (!n)
      return new Error("Failed to find demuxer by probing fragment data");
    const o = this.demuxer, c = this.remuxer, l = n.remux, d = n.demux;
    (!c || !(c instanceof l)) && (this.remuxer = new l(i, t, s, this.logger)), (!o || !(o instanceof d)) && (this.demuxer = new d(i, t, s, this.logger), this.probe = d.probe);
  }
  needsProbing(e, t) {
    return !this.demuxer || !this.remuxer || e || t;
  }
  getDecrypter() {
    let e = this.decrypter;
    return e || (e = this.decrypter = new Zd(this.config)), e;
  }
}
function rR(r, e) {
  let t = null;
  return r.byteLength > 0 && (e == null ? void 0 : e.key) != null && e.iv !== null && e.method != null && (t = e), t;
}
const R0 = (r) => ({
  remuxResult: {},
  chunkMeta: r
});
function bn(r) {
  return "then" in r && r.then instanceof Function;
}
class nR {
  constructor(e, t, i, s, n) {
    this.audioCodec = void 0, this.videoCodec = void 0, this.initSegmentData = void 0, this.duration = void 0, this.defaultInitPts = void 0, this.audioCodec = e, this.videoCodec = t, this.initSegmentData = i, this.duration = s, this.defaultInitPts = n || null;
  }
}
class aR {
  constructor(e, t, i, s, n, a) {
    this.discontinuity = void 0, this.contiguous = void 0, this.accurateTimeOffset = void 0, this.trackSwitch = void 0, this.timeOffset = void 0, this.initSegmentChange = void 0, this.discontinuity = e, this.contiguous = t, this.accurateTimeOffset = i, this.trackSwitch = s, this.timeOffset = n, this.initSegmentChange = a;
  }
}
let Fp = 0;
class O_ {
  constructor(e, t, i, s) {
    this.error = null, this.hls = void 0, this.id = void 0, this.instanceNo = Fp++, this.observer = void 0, this.frag = null, this.part = null, this.useWorker = void 0, this.workerContext = null, this.transmuxer = null, this.onTransmuxComplete = void 0, this.onFlush = void 0, this.onWorkerMessage = (c) => {
      const l = c.data, d = this.hls;
      if (!(!d || !(l != null && l.event) || l.instanceNo !== this.instanceNo))
        switch (l.event) {
          case "init": {
            var h;
            const u = (h = this.workerContext) == null ? void 0 : h.objectURL;
            u && self.URL.revokeObjectURL(u);
            break;
          }
          case "transmuxComplete": {
            this.handleTransmuxComplete(l.data);
            break;
          }
          case "flush": {
            this.onFlush(l.data);
            break;
          }
          case "workerLog": {
            d.logger[l.data.logType] && d.logger[l.data.logType](l.data.message);
            break;
          }
          default: {
            l.data = l.data || {}, l.data.frag = this.frag, l.data.part = this.part, l.data.id = this.id, d.trigger(l.event, l.data);
            break;
          }
        }
    }, this.onWorkerError = (c) => {
      if (!this.hls)
        return;
      const l = new Error(`${c.message}  (${c.filename}:${c.lineno})`);
      this.hls.config.enableWorker = !1, this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`), this.hls.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.INTERNAL_EXCEPTION,
        fatal: !1,
        event: "demuxerWorker",
        error: l
      });
    };
    const n = e.config;
    this.hls = e, this.id = t, this.useWorker = !!n.enableWorker, this.onTransmuxComplete = i, this.onFlush = s;
    const a = (c, l) => {
      l = l || {}, l.frag = this.frag || void 0, c === T.ERROR && (l = l, l.parent = this.id, l.part = this.part, this.error = l.error), this.hls.trigger(c, l);
    };
    this.observer = new zd(), this.observer.on(T.FRAG_DECRYPTED, a), this.observer.on(T.ERROR, a);
    const o = qf(n.preferManagedMediaSource);
    if (this.useWorker && typeof Worker < "u") {
      const c = this.hls.logger;
      if (n.workerPath || d8()) {
        try {
          n.workerPath ? (c.log(`loading Web Worker ${n.workerPath} for "${t}"`), this.workerContext = u8(n.workerPath)) : (c.log(`injecting Web Worker for "${t}"`), this.workerContext = h8());
          const {
            worker: d
          } = this.workerContext;
          d.addEventListener("message", this.onWorkerMessage), d.addEventListener("error", this.onWorkerError), d.postMessage({
            instanceNo: this.instanceNo,
            cmd: "init",
            typeSupported: o,
            id: t,
            config: Ze(n)
          });
        } catch (d) {
          c.warn(`Error setting up "${t}" Web Worker, fallback to inline`, d), this.terminateWorker(), this.error = null, this.transmuxer = new Bp(this.observer, o, n, "", t, e.logger);
        }
        return;
      }
    }
    this.transmuxer = new Bp(this.observer, o, n, "", t, e.logger);
  }
  reset() {
    if (this.frag = null, this.part = null, this.workerContext) {
      const e = this.instanceNo;
      this.instanceNo = Fp++;
      const t = this.hls.config, i = qf(t.preferManagedMediaSource);
      this.workerContext.worker.postMessage({
        instanceNo: this.instanceNo,
        cmd: "reset",
        resetNo: e,
        typeSupported: i,
        id: this.id,
        config: Ze(t)
      });
    }
  }
  terminateWorker() {
    if (this.workerContext) {
      const {
        worker: e
      } = this.workerContext;
      this.workerContext = null, e.removeEventListener("message", this.onWorkerMessage), e.removeEventListener("error", this.onWorkerError), f8(this.hls.config.workerPath);
    }
  }
  destroy() {
    if (this.workerContext)
      this.terminateWorker(), this.onWorkerMessage = this.onWorkerError = null;
    else {
      const t = this.transmuxer;
      t && (t.destroy(), this.transmuxer = null);
    }
    const e = this.observer;
    e && e.removeAllListeners(), this.frag = null, this.part = null, this.observer = null, this.hls = null;
  }
  push(e, t, i, s, n, a, o, c, l, d) {
    var h, u;
    l.transmuxing.start = self.performance.now();
    const {
      instanceNo: f,
      transmuxer: p
    } = this, m = a ? a.start : n.start, g = n.decryptdata, x = this.frag, _ = !(x && n.cc === x.cc), v = !(x && l.level === x.level), E = x ? l.sn - x.sn : -1, b = this.part ? l.part - this.part.index : -1, A = E === 0 && l.id > 1 && l.id === (x == null ? void 0 : x.stats.chunkCount), C = !v && (E === 1 || E === 0 && (b === 1 || A && b <= 0)), I = self.performance.now();
    (v || E || n.stats.parsing.start === 0) && (n.stats.parsing.start = I), a && (b || !C) && (a.stats.parsing.start = I);
    const L = !(x && ((h = n.initSegment) == null ? void 0 : h.url) === ((u = x.initSegment) == null ? void 0 : u.url)), R = new aR(_, C, c, v, m, L);
    if (!C || _ || L) {
      this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part > -1 ? " part: " + l.part : ""} ${this.id === te.MAIN ? "level" : "track"}: ${l.level} id: ${l.id}
        discontinuity: ${_}
        trackSwitch: ${v}
        contiguous: ${C}
        accurateTimeOffset: ${c}
        timeOffset: ${m}
        initSegmentChange: ${L}`);
      const D = new nR(i, s, t, o, d);
      this.configureTransmuxer(D);
    }
    if (this.frag = n, this.part = a, this.workerContext)
      this.workerContext.worker.postMessage({
        instanceNo: f,
        cmd: "demux",
        data: e,
        decryptdata: g,
        chunkMeta: l,
        state: R
      }, e instanceof ArrayBuffer ? [e] : []);
    else if (p) {
      const D = p.push(e, g, l, R);
      bn(D) ? D.then((M) => {
        this.handleTransmuxComplete(M);
      }).catch((M) => {
        this.transmuxerError(M, l, "transmuxer-interface push error");
      }) : this.handleTransmuxComplete(D);
    }
  }
  flush(e) {
    e.transmuxing.start = self.performance.now();
    const {
      instanceNo: t,
      transmuxer: i
    } = this;
    if (this.workerContext)
      this.workerContext.worker.postMessage({
        instanceNo: t,
        cmd: "flush",
        chunkMeta: e
      });
    else if (i) {
      const s = i.flush(e);
      bn(s) ? s.then((n) => {
        this.handleFlushResult(n, e);
      }).catch((n) => {
        this.transmuxerError(n, e, "transmuxer-interface flush error");
      }) : this.handleFlushResult(s, e);
    }
  }
  transmuxerError(e, t, i) {
    this.hls && (this.error = e, this.hls.trigger(T.ERROR, {
      type: ie.MEDIA_ERROR,
      details: V.FRAG_PARSING_ERROR,
      chunkMeta: t,
      frag: this.frag || void 0,
      part: this.part || void 0,
      fatal: !1,
      error: e,
      err: e,
      reason: i
    }));
  }
  handleFlushResult(e, t) {
    e.forEach((i) => {
      this.handleTransmuxComplete(i);
    }), this.onFlush(t);
  }
  configureTransmuxer(e) {
    const {
      instanceNo: t,
      transmuxer: i
    } = this;
    this.workerContext ? this.workerContext.worker.postMessage({
      instanceNo: t,
      cmd: "configure",
      config: e
    }) : i && i.configure(e);
  }
  handleTransmuxComplete(e) {
    e.chunkMeta.transmuxing.end = self.performance.now(), this.onTransmuxComplete(e);
  }
}
const Op = 100;
class oR extends Yd {
  constructor(e, t, i) {
    super(e, t, i, "audio-stream-controller", te.AUDIO), this.mainAnchor = null, this.mainFragLoading = null, this.audioOnly = !1, this.bufferedTrack = null, this.switchingTrack = null, this.trackId = -1, this.waitingData = null, this.mainDetails = null, this.flushing = !1, this.bufferFlushed = !1, this.cachedTrackLoadedData = null, this.registerListeners();
  }
  onHandlerDestroying() {
    this.unregisterListeners(), super.onHandlerDestroying(), this.resetItem();
  }
  resetItem() {
    this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls: e
    } = this;
    e.on(T.LEVEL_LOADED, this.onLevelLoaded, this), e.on(T.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this), e.on(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.on(T.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this), e.on(T.BUFFER_RESET, this.onBufferReset, this), e.on(T.BUFFER_CREATED, this.onBufferCreated, this), e.on(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.on(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.on(T.INIT_PTS_FOUND, this.onInitPtsFound, this), e.on(T.FRAG_LOADING, this.onFragLoading, this), e.on(T.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (super.unregisterListeners(), e.off(T.LEVEL_LOADED, this.onLevelLoaded, this), e.off(T.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this), e.off(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.off(T.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this), e.off(T.BUFFER_RESET, this.onBufferReset, this), e.off(T.BUFFER_CREATED, this.onBufferCreated, this), e.off(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.off(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.off(T.INIT_PTS_FOUND, this.onInitPtsFound, this), e.off(T.FRAG_LOADING, this.onFragLoading, this), e.off(T.FRAG_BUFFERED, this.onFragBuffered, this));
  }
  // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  onInitPtsFound(e, {
    frag: t,
    id: i,
    initPTS: s,
    timescale: n,
    trackId: a
  }) {
    if (i === te.MAIN) {
      const o = t.cc, c = this.fragCurrent;
      if (this.initPTS[o] = {
        baseTime: s,
        timescale: n,
        trackId: a
      }, this.log(`InitPTS for cc: ${o} found from main: ${s / n} (${s}/${n}) trackId: ${a}`), this.mainAnchor = t, this.state === K.WAITING_INIT_PTS) {
        const l = this.waitingData;
        (!l && !this.loadingParts || l && l.frag.cc !== o) && this.syncWithAnchor(t, l == null ? void 0 : l.frag);
      } else !this.hls.hasEnoughToStart && c && c.cc !== o ? (c.abortRequests(), this.syncWithAnchor(t, c)) : this.state === K.IDLE && this.tick();
    }
  }
  getLoadPosition() {
    return !this.startFragRequested && this.nextLoadPosition >= 0 ? this.nextLoadPosition : super.getLoadPosition();
  }
  syncWithAnchor(e, t) {
    var i;
    const s = ((i = this.mainFragLoading) == null ? void 0 : i.frag) || null;
    if (t && (s == null ? void 0 : s.cc) === t.cc)
      return;
    const n = (s || e).cc, a = this.getLevelDetails(), o = this.getLoadPosition(), c = s_(a, n, o);
    c && (this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`), this.startFragRequested = !1, this.nextLoadPosition = c.start, this.resetLoadingState(), this.state === K.IDLE && this.doTickIdle());
  }
  startLoad(e, t) {
    if (!this.levels) {
      this.startPosition = e, this.state = K.STOPPED;
      return;
    }
    const i = this.lastCurrentTime;
    this.stopLoad(), this.setInterval(Op), i > 0 && e === -1 ? (this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`), e = i, this.state = K.IDLE) : this.state = K.WAITING_TRACK, this.nextLoadPosition = this.lastCurrentTime = e + this.timelineOffset, this.startPosition = t ? -1 : e, this.tick();
  }
  doTick() {
    switch (this.state) {
      case K.IDLE:
        this.doTickIdle();
        break;
      case K.WAITING_TRACK: {
        const {
          levels: e,
          trackId: t
        } = this, i = e == null ? void 0 : e[t], s = i == null ? void 0 : i.details;
        if (s && !this.waitForLive(i)) {
          if (this.waitForCdnTuneIn(s))
            break;
          this.state = K.WAITING_INIT_PTS;
        }
        break;
      }
      case K.FRAG_LOADING_WAITING_RETRY: {
        this.checkRetryDate();
        break;
      }
      case K.WAITING_INIT_PTS: {
        const e = this.waitingData;
        if (e) {
          const {
            frag: t,
            part: i,
            cache: s,
            complete: n
          } = e, a = this.mainAnchor;
          if (this.initPTS[t.cc] !== void 0) {
            this.waitingData = null, this.state = K.FRAG_LOADING;
            const o = s.flush().buffer, c = {
              frag: t,
              part: i,
              payload: o,
              networkDetails: null
            };
            this._handleFragmentLoadProgress(c), n && super._handleFragmentLoadComplete(c);
          } else a && a.cc !== e.frag.cc && this.syncWithAnchor(a, e.frag);
        } else
          this.state = K.IDLE;
      }
    }
    this.onTickEnd();
  }
  resetLoadingState() {
    const e = this.waitingData;
    e && (this.fragmentTracker.removeFragment(e.frag), this.waitingData = null), super.resetLoadingState();
  }
  onTickEnd() {
    const {
      media: e
    } = this;
    e != null && e.readyState && (this.lastCurrentTime = e.currentTime);
  }
  doTickIdle() {
    var e;
    const {
      hls: t,
      levels: i,
      media: s,
      trackId: n
    } = this, a = t.config;
    if (!this.buffering || !s && !this.primaryPrefetch && (this.startFragRequested || !a.startFragPrefetch) || !(i != null && i[n]))
      return;
    const o = i[n], c = o.details;
    if (!c || this.waitForLive(o) || this.waitForCdnTuneIn(c)) {
      this.state = K.WAITING_TRACK, this.startFragRequested = !1;
      return;
    }
    const l = this.mediaBuffer ? this.mediaBuffer : this.media;
    this.bufferFlushed && l && (this.bufferFlushed = !1, this.afterBufferFlushed(l, Oe.AUDIO, te.AUDIO));
    const d = this.getFwdBufferInfo(l, te.AUDIO);
    if (d === null)
      return;
    if (!this.switchingTrack && this._streamEnded(d, c)) {
      t.trigger(T.BUFFER_EOS, {
        type: "audio"
      }), this.state = K.ENDED;
      return;
    }
    const h = d.len, u = t.maxBufferLength, f = c.fragments, p = f[0].start, m = this.getLoadPosition(), g = this.flushing ? m : d.end;
    if (this.switchingTrack && s) {
      const v = m;
      c.PTSKnown && v < p && (d.end > p || d.nextStart) && (this.log("Alt audio track ahead of main track, seek to start of alt audio track"), s.currentTime = p + 0.05);
    }
    if (h >= u && !this.switchingTrack && g < f[f.length - 1].start)
      return;
    let x = this.getNextFragment(g, c);
    if (x && this.isLoopLoading(x, g) && (x = this.getNextFragmentLoopLoading(x, c, d, te.MAIN, u)), !x) {
      this.bufferFlushed = !0;
      return;
    }
    let _ = ((e = this.mainFragLoading) == null ? void 0 : e.frag) || null;
    if (!this.audioOnly && this.startFragRequested && _ && et(x) && !x.endList && (!c.live || !this.loadingParts && g < this.hls.liveSyncPosition) && (this.fragmentTracker.getState(_) === nt.OK && (this.mainFragLoading = _ = null), _ && et(_))) {
      if (x.start > _.end) {
        const E = this.fragmentTracker.getFragAtPos(g, te.MAIN);
        E && E.end > _.end && (_ = E, this.mainFragLoading = {
          frag: E,
          targetBufferTime: null
        });
      }
      if (x.start > _.end)
        return;
    }
    this.loadFragment(x, o, g);
  }
  onMediaDetaching(e, t) {
    this.bufferFlushed = this.flushing = !1, super.onMediaDetaching(e, t);
  }
  onAudioTracksUpdated(e, {
    audioTracks: t
  }) {
    this.resetTransmuxer(), this.levels = t.map((i) => new En(i));
  }
  onAudioTrackSwitching(e, t) {
    const i = !!t.url;
    this.trackId = t.id;
    const {
      fragCurrent: s
    } = this;
    s && (s.abortRequests(), this.removeUnbufferedFrags(s.start)), this.resetLoadingState(), i ? (this.switchingTrack = t, this.flushAudioIfNeeded(t), this.state !== K.STOPPED && (this.setInterval(Op), this.state = K.IDLE, this.tick())) : (this.resetTransmuxer(), this.switchingTrack = null, this.bufferedTrack = t, this.clearInterval());
  }
  onManifestLoading() {
    super.onManifestLoading(), this.bufferFlushed = this.flushing = this.audioOnly = !1, this.resetItem(), this.trackId = -1;
  }
  onLevelLoaded(e, t) {
    this.mainDetails = t.details;
    const i = this.cachedTrackLoadedData;
    i && (this.cachedTrackLoadedData = null, this.onAudioTrackLoaded(T.AUDIO_TRACK_LOADED, i));
  }
  onAudioTrackLoaded(e, t) {
    var i;
    const {
      levels: s
    } = this, {
      details: n,
      id: a,
      groupId: o,
      track: c
    } = t;
    if (!s) {
      this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);
      return;
    }
    const l = this.mainDetails;
    if (!l || n.endCC > l.endCC || l.expired) {
      this.cachedTrackLoadedData = t, this.state !== K.STOPPED && (this.state = K.WAITING_TRACK);
      return;
    }
    this.cachedTrackLoadedData = null, this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn ? `[part-${n.lastPartSn}-${n.lastPartIndex}]` : ""},duration:${n.totalduration}`);
    const d = s[a];
    let h = 0;
    if (n.live || (i = d.details) != null && i.live) {
      if (this.checkLiveUpdate(n), n.deltaUpdateFailed)
        return;
      if (d.details) {
        var u;
        h = this.alignPlaylists(n, d.details, (u = this.levelLastLoaded) == null ? void 0 : u.details);
      }
      n.alignedSliding || (__(n, l), n.alignedSliding || oo(n, l), h = n.fragmentStart);
    }
    d.details = n, this.levelLastLoaded = d, this.startFragRequested || this.setStartPosition(l, h), this.hls.trigger(T.AUDIO_TRACK_UPDATED, {
      details: n,
      id: a,
      groupId: t.groupId
    }), this.state === K.WAITING_TRACK && !this.waitForCdnTuneIn(n) && (this.state = K.IDLE), this.tick();
  }
  _handleFragmentLoadProgress(e) {
    var t;
    const i = e.frag, {
      part: s,
      payload: n
    } = e, {
      config: a,
      trackId: o,
      levels: c
    } = this;
    if (!c) {
      this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);
      return;
    }
    const l = c[o];
    if (!l) {
      this.warn("Audio track is undefined on fragment load progress");
      return;
    }
    const d = l.details;
    if (!d) {
      this.warn("Audio track details undefined on fragment load progress"), this.removeUnbufferedFrags(i.start);
      return;
    }
    const h = a.defaultAudioCodec || l.audioCodec || "mp4a.40.2";
    let u = this.transmuxer;
    u || (u = this.transmuxer = new O_(this.hls, te.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)));
    const f = this.initPTS[i.cc], p = (t = i.initSegment) == null ? void 0 : t.data;
    if (f !== void 0) {
      const g = s ? s.index : -1, x = g !== -1, _ = new $d(i.level, i.sn, i.stats.chunkCount, n.byteLength, g, x);
      u.push(n, p, h, "", i, s, d.totalduration, !1, _, f);
    } else {
      this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);
      const {
        cache: m
      } = this.waitingData = this.waitingData || {
        frag: i,
        part: s,
        cache: new y_(),
        complete: !1
      };
      m.push(new Uint8Array(n)), this.state !== K.STOPPED && (this.state = K.WAITING_INIT_PTS);
    }
  }
  _handleFragmentLoadComplete(e) {
    if (this.waitingData) {
      this.waitingData.complete = !0;
      return;
    }
    super._handleFragmentLoadComplete(e);
  }
  onBufferReset() {
    this.mediaBuffer = null;
  }
  onBufferCreated(e, t) {
    this.bufferFlushed = this.flushing = !1;
    const i = t.tracks.audio;
    i && (this.mediaBuffer = i.buffer || null);
  }
  onFragLoading(e, t) {
    !this.audioOnly && t.frag.type === te.MAIN && et(t.frag) && (this.mainFragLoading = t, this.state === K.IDLE && this.tick());
  }
  onFragBuffered(e, t) {
    const {
      frag: i,
      part: s
    } = t;
    if (i.type !== te.AUDIO) {
      !this.audioOnly && i.type === te.MAIN && !i.elementaryStreams.video && !i.elementaryStreams.audiovideo && (this.audioOnly = !0, this.mainFragLoading = null);
      return;
    }
    if (this.fragContextChanged(i)) {
      this.warn(`Fragment ${i.sn}${s ? " p: " + s.index : ""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : "false"}`);
      return;
    }
    if (et(i)) {
      this.fragPrevious = i;
      const n = this.switchingTrack;
      n && (this.bufferedTrack = n, this.switchingTrack = null, this.hls.trigger(T.AUDIO_TRACK_SWITCHED, we({}, n)));
    }
    this.fragBufferedComplete(i, s), this.media && this.tick();
  }
  onError(e, t) {
    var i;
    if (t.fatal) {
      this.state = K.ERROR;
      return;
    }
    switch (t.details) {
      case V.FRAG_GAP:
      case V.FRAG_PARSING_ERROR:
      case V.FRAG_DECRYPT_ERROR:
      case V.FRAG_LOAD_ERROR:
      case V.FRAG_LOAD_TIMEOUT:
      case V.KEY_LOAD_ERROR:
      case V.KEY_LOAD_TIMEOUT:
        this.onFragmentOrKeyLoadError(te.AUDIO, t);
        break;
      case V.AUDIO_TRACK_LOAD_ERROR:
      case V.AUDIO_TRACK_LOAD_TIMEOUT:
      case V.LEVEL_PARSING_ERROR:
        !t.levelRetry && this.state === K.WAITING_TRACK && ((i = t.context) == null ? void 0 : i.type) === me.AUDIO_TRACK && (this.state = K.IDLE);
        break;
      case V.BUFFER_ADD_CODEC_ERROR:
      case V.BUFFER_APPEND_ERROR:
        if (t.parent !== "audio")
          return;
        this.reduceLengthAndFlushBuffer(t) || this.resetLoadingState();
        break;
      case V.BUFFER_FULL_ERROR:
        if (t.parent !== "audio")
          return;
        this.reduceLengthAndFlushBuffer(t) && (this.bufferedTrack = null, super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio"));
        break;
      case V.INTERNAL_EXCEPTION:
        this.recoverWorkerError(t);
        break;
    }
  }
  onBufferFlushing(e, {
    type: t
  }) {
    t !== Oe.VIDEO && (this.flushing = !0);
  }
  onBufferFlushed(e, {
    type: t
  }) {
    if (t !== Oe.VIDEO) {
      this.flushing = !1, this.bufferFlushed = !0, this.state === K.ENDED && (this.state = K.IDLE);
      const i = this.mediaBuffer || this.media;
      i && (this.afterBufferFlushed(i, t, te.AUDIO), this.tick());
    }
  }
  _handleTransmuxComplete(e) {
    var t;
    const i = "audio", {
      hls: s
    } = this, {
      remuxResult: n,
      chunkMeta: a
    } = e, o = this.getCurrentContext(a);
    if (!o) {
      this.resetWhenMissingContext(a);
      return;
    }
    const {
      frag: c,
      part: l,
      level: d
    } = o, {
      details: h
    } = d, {
      audio: u,
      text: f,
      id3: p,
      initSegment: m
    } = n;
    if (this.fragContextChanged(c) || !h) {
      this.fragmentTracker.removeFragment(c);
      return;
    }
    if (this.state = K.PARSING, this.switchingTrack && u && this.completeAudioSwitch(this.switchingTrack), m != null && m.tracks) {
      const g = c.initSegment || c;
      if (this.unhandledEncryptionError(m, c))
        return;
      this._bufferInitSegment(d, m.tracks, g, a), s.trigger(T.FRAG_PARSING_INIT_SEGMENT, {
        frag: g,
        id: i,
        tracks: m.tracks
      });
    }
    if (u) {
      const {
        startPTS: g,
        endPTS: x,
        startDTS: _,
        endDTS: v
      } = u;
      l && (l.elementaryStreams[Oe.AUDIO] = {
        startPTS: g,
        endPTS: x,
        startDTS: _,
        endDTS: v
      }), c.setElementaryStreamInfo(Oe.AUDIO, g, x, _, v), this.bufferFragmentData(u, c, l, a);
    }
    if (p != null && (t = p.samples) != null && t.length) {
      const g = Me({
        id: i,
        frag: c,
        details: h
      }, p);
      s.trigger(T.FRAG_PARSING_METADATA, g);
    }
    if (f) {
      const g = Me({
        id: i,
        frag: c,
        details: h
      }, f);
      s.trigger(T.FRAG_PARSING_USERDATA, g);
    }
  }
  _bufferInitSegment(e, t, i, s) {
    if (this.state !== K.PARSING || (t.video && delete t.video, t.audiovideo && delete t.audiovideo, !t.audio))
      return;
    const n = t.audio;
    n.id = te.AUDIO;
    const a = e.audioCodec;
    this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`), a && a.split(",").length === 1 && (n.levelCodec = a), this.hls.trigger(T.BUFFER_CODECS, t);
    const o = n.initSegment;
    if (o != null && o.byteLength) {
      const c = {
        type: "audio",
        frag: i,
        part: null,
        chunkMeta: s,
        parent: i.type,
        data: o
      };
      this.hls.trigger(T.BUFFER_APPENDING, c);
    }
    this.tickImmediate();
  }
  loadFragment(e, t, i) {
    const s = this.fragmentTracker.getState(e);
    if (this.switchingTrack || s === nt.NOT_LOADED || s === nt.PARTIAL) {
      var n;
      if (!et(e))
        this._loadInitSegment(e, t);
      else if ((n = t.details) != null && n.live && !this.initPTS[e.cc]) {
        this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`), this.state = K.WAITING_INIT_PTS;
        const a = this.mainDetails;
        a && a.fragmentStart !== t.details.fragmentStart && oo(t.details, a);
      } else
        super.loadFragment(e, t, i);
    } else
      this.clearTrackerIfNeeded(e);
  }
  flushAudioIfNeeded(e) {
    if (this.media && this.bufferedTrack) {
      const {
        name: t,
        lang: i,
        assocLang: s,
        characteristics: n,
        audioCodec: a,
        channels: o
      } = this.bufferedTrack;
      Bs({
        name: t,
        lang: i,
        assocLang: s,
        characteristics: n,
        audioCodec: a,
        channels: o
      }, e, Ls) || (so(e.url, this.hls) ? (this.log("Switching audio track : flushing all audio"), super.flushMainBuffer(0, Number.POSITIVE_INFINITY, "audio"), this.bufferedTrack = null) : this.bufferedTrack = e);
    }
  }
  completeAudioSwitch(e) {
    const {
      hls: t
    } = this;
    this.flushAudioIfNeeded(e), this.bufferedTrack = e, this.switchingTrack = null, t.trigger(T.AUDIO_TRACK_SWITCHED, we({}, e));
  }
}
class ih extends qt {
  constructor(e, t) {
    super(t, e.logger), this.hls = void 0, this.canLoad = !1, this.timer = -1, this.hls = e;
  }
  destroy() {
    this.clearTimer(), this.hls = this.log = this.warn = null;
  }
  clearTimer() {
    this.timer !== -1 && (self.clearTimeout(this.timer), this.timer = -1);
  }
  startLoad() {
    this.canLoad = !0, this.loadPlaylist();
  }
  stopLoad() {
    this.canLoad = !1, this.clearTimer();
  }
  switchParams(e, t, i) {
    const s = t == null ? void 0 : t.renditionReports;
    if (s) {
      let n = -1;
      for (let a = 0; a < s.length; a++) {
        const o = s[a];
        let c;
        try {
          c = new self.URL(o.URI, t.url).href;
        } catch (l) {
          this.warn(`Could not construct new URL for Rendition Report: ${l}`), c = o.URI || "";
        }
        if (c === e) {
          n = a;
          break;
        } else c === e.substring(0, c.length) && (n = a);
      }
      if (n !== -1) {
        const a = s[n], o = parseInt(a["LAST-MSN"]) || t.lastPartSn;
        let c = parseInt(a["LAST-PART"]) || t.lastPartIndex;
        if (this.hls.config.lowLatencyMode) {
          const d = Math.min(t.age - t.partTarget, t.targetduration);
          c >= 0 && d > t.partTarget && (c += 1);
        }
        const l = i && ep(i);
        return new tp(o, c >= 0 ? c : void 0, l);
      }
    }
  }
  loadPlaylist(e) {
    this.clearTimer();
  }
  loadingPlaylist(e, t) {
    this.clearTimer();
  }
  shouldLoadPlaylist(e) {
    return this.canLoad && !!e && !!e.url && (!e.details || e.details.live);
  }
  getUrlWithDirectives(e, t) {
    if (t)
      try {
        return t.addDirectives(e);
      } catch (i) {
        this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`);
      }
    return e;
  }
  playlistLoaded(e, t, i) {
    const {
      details: s,
      stats: n
    } = t, a = self.performance.now(), o = n.loading.first ? Math.max(0, a - n.loading.first) : 0;
    s.advancedDateTime = Date.now() - o;
    const c = this.hls.config.timelineOffset;
    if (c !== s.appliedTimelineOffset) {
      const d = Math.max(c || 0, 0);
      s.appliedTimelineOffset = d, s.fragments.forEach((h) => {
        h.setStart(h.playlistOffset + d);
      });
    }
    if (s.live || i != null && i.live) {
      const d = "levelInfo" in t ? t.levelInfo : t.track;
      if (s.reloaded(i), i && s.fragments.length > 0) {
        qC(i, s, this);
        const _ = s.playlistParsingError;
        if (_) {
          this.warn(_);
          const v = this.hls;
          if (!v.config.ignorePlaylistParsingErrors) {
            var l;
            const {
              networkDetails: E
            } = t;
            v.trigger(T.ERROR, {
              type: ie.NETWORK_ERROR,
              details: V.LEVEL_PARSING_ERROR,
              fatal: !1,
              url: s.url,
              error: _,
              reason: _.message,
              level: t.level || void 0,
              parent: (l = s.fragments[0]) == null ? void 0 : l.type,
              networkDetails: E,
              stats: n
            });
            return;
          }
          s.playlistParsingError = null;
        }
      }
      s.requestScheduled === -1 && (s.requestScheduled = n.loading.start);
      const h = this.hls.mainForwardBufferInfo, u = h ? h.end - h.len : 0, f = (s.edge - u) * 1e3, p = u_(s, f);
      if (s.requestScheduled + p < a ? s.requestScheduled = a : s.requestScheduled += p, this.log(`live playlist ${e} ${s.advanced ? "REFRESHED " + s.lastPartSn + "-" + s.lastPartIndex : s.updated ? "UPDATED" : "MISSED"}`), !this.canLoad || !s.live)
        return;
      let m, g, x;
      if (s.canBlockReload && s.endSN && s.advanced) {
        const _ = this.hls.config.lowLatencyMode, v = s.lastPartSn, E = s.endSN, b = s.lastPartIndex, A = b !== -1, C = v === E;
        A ? C ? (g = E + 1, x = _ ? 0 : b) : (g = v, x = _ ? b + 1 : s.maxPartIndex) : g = E + 1;
        const I = s.age, L = I + s.ageHeader;
        let R = Math.min(L - s.partTarget, s.targetduration * 1.5);
        if (R > 0) {
          if (L > s.targetduration * 3)
            this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`), g = void 0, x = void 0;
          else if (i != null && i.tuneInGoal && L - s.partTarget > i.tuneInGoal)
            this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${R} with playlist age: ${s.age}`), R = 0;
          else {
            const D = Math.floor(R / s.targetduration);
            if (g += D, x !== void 0) {
              const M = Math.round(R % s.targetduration / s.partTarget);
              x += M;
            }
            this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${R} skip sn ${D} to part ${x}`);
          }
          s.tuneInGoal = R;
        }
        if (m = this.getDeliveryDirectives(s, t.deliveryDirectives, g, x), _ || !C) {
          s.requestScheduled = a, this.loadingPlaylist(d, m);
          return;
        }
      } else (s.canBlockReload || s.canSkipUntil) && (m = this.getDeliveryDirectives(s, t.deliveryDirectives, g, x));
      m && g !== void 0 && s.canBlockReload && (s.requestScheduled = n.loading.first + Math.max(p - o * 2, p / 2)), this.scheduleLoading(d, m, s);
    } else
      this.clearTimer();
  }
  scheduleLoading(e, t, i) {
    const s = i || e.details;
    if (!s) {
      this.loadingPlaylist(e, t);
      return;
    }
    const n = self.performance.now(), a = s.requestScheduled;
    if (n >= a) {
      this.loadingPlaylist(e, t);
      return;
    }
    const o = a - n;
    this.log(`reload live playlist ${e.name || e.bitrate + "bps"} in ${Math.round(o)} ms`), this.clearTimer(), this.timer = self.setTimeout(() => this.loadingPlaylist(e, t), o);
  }
  getDeliveryDirectives(e, t, i, s) {
    let n = ep(e);
    return t != null && t.skip && e.deltaUpdateFailed && (i = t.msn, s = t.part, n = Da.No), new tp(i, s, n);
  }
  checkRetry(e) {
    const t = e.details, i = ro(e), s = e.errorAction, {
      action: n,
      retryCount: a = 0,
      retryConfig: o
    } = s || {}, c = !!s && !!o && (n === ft.RetryRequest || !s.resolved && n === ft.SendAlternateToPenaltyBox);
    if (c) {
      var l;
      if (a >= o.maxNumRetry)
        return !1;
      if (i && (l = e.context) != null && l.deliveryDirectives)
        this.warn(`Retrying playlist loading ${a + 1}/${o.maxNumRetry} after "${t}" without delivery-directives`), this.loadPlaylist();
      else {
        const d = Hd(o, a);
        this.clearTimer(), this.timer = self.setTimeout(() => this.loadPlaylist(), d), this.warn(`Retrying playlist loading ${a + 1}/${o.maxNumRetry} after "${t}" in ${d}ms`);
      }
      e.levelRetry = !0, s.resolved = !0;
    }
    return c;
  }
}
function N_(r, e) {
  if (r.length !== e.length)
    return !1;
  for (let t = 0; t < r.length; t++)
    if (!An(r[t].attrs, e[t].attrs))
      return !1;
  return !0;
}
function An(r, e, t) {
  const i = r["STABLE-RENDITION-ID"];
  return i && !t ? i === e["STABLE-RENDITION-ID"] : !(t || ["LANGUAGE", "NAME", "CHARACTERISTICS", "AUTOSELECT", "DEFAULT", "FORCED", "ASSOC-LANGUAGE"]).some((s) => r[s] !== e[s]);
}
function Gc(r, e) {
  return e.label.toLowerCase() === r.name.toLowerCase() && (!e.language || e.language.toLowerCase() === (r.lang || "").toLowerCase());
}
class lR extends ih {
  constructor(e) {
    super(e, "audio-track-controller"), this.tracks = [], this.groupIds = null, this.tracksInGroup = [], this.trackId = -1, this.currentTrack = null, this.selectDefaultTrack = !0, this.registerListeners();
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.LEVEL_LOADING, this.onLevelLoading, this), e.on(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.on(T.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.LEVEL_LOADING, this.onLevelLoading, this), e.off(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.off(T.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this), e.off(T.ERROR, this.onError, this);
  }
  destroy() {
    this.unregisterListeners(), this.tracks.length = 0, this.tracksInGroup.length = 0, this.currentTrack = null, super.destroy();
  }
  onManifestLoading() {
    this.tracks = [], this.tracksInGroup = [], this.groupIds = null, this.currentTrack = null, this.trackId = -1, this.selectDefaultTrack = !0;
  }
  onManifestParsed(e, t) {
    this.tracks = t.audioTracks || [];
  }
  onAudioTrackLoaded(e, t) {
    const {
      id: i,
      groupId: s,
      details: n
    } = t, a = this.tracksInGroup[i];
    if (!a || a.groupId !== s) {
      this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a == null ? void 0 : a.groupId}`);
      return;
    }
    const o = a.details;
    a.details = t.details, this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`), i === this.trackId && this.playlistLoaded(i, t, o);
  }
  onLevelLoading(e, t) {
    this.switchLevel(t.level);
  }
  onLevelSwitching(e, t) {
    this.switchLevel(t.level);
  }
  switchLevel(e) {
    const t = this.hls.levels[e];
    if (!t)
      return;
    const i = t.audioGroups || null, s = this.groupIds;
    let n = this.currentTrack;
    if (!i || (s == null ? void 0 : s.length) !== (i == null ? void 0 : i.length) || i != null && i.some((o) => (s == null ? void 0 : s.indexOf(o)) === -1)) {
      this.groupIds = i, this.trackId = -1, this.currentTrack = null;
      const o = this.tracks.filter((u) => !i || i.indexOf(u.groupId) !== -1);
      if (o.length)
        this.selectDefaultTrack && !o.some((u) => u.default) && (this.selectDefaultTrack = !1), o.forEach((u, f) => {
          u.id = f;
        });
      else if (!n && !this.tracksInGroup.length)
        return;
      this.tracksInGroup = o;
      const c = this.hls.config.audioPreference;
      if (!n && c) {
        const u = Di(c, o, Ls);
        if (u > -1)
          n = o[u];
        else {
          const f = Di(c, this.tracks);
          n = this.tracks[f];
        }
      }
      let l = this.findTrackId(n);
      l === -1 && n && (l = this.findTrackId(null));
      const d = {
        audioTracks: o
      };
      this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i == null ? void 0 : i.join(",")}`), this.hls.trigger(T.AUDIO_TRACKS_UPDATED, d);
      const h = this.trackId;
      if (l !== -1 && h === -1)
        this.setAudioTrack(l);
      else if (o.length && h === -1) {
        var a;
        const u = new Error(`No audio track selected for current audio group-ID(s): ${(a = this.groupIds) == null ? void 0 : a.join(",")} track count: ${o.length}`);
        this.warn(u.message), this.hls.trigger(T.ERROR, {
          type: ie.MEDIA_ERROR,
          details: V.AUDIO_TRACK_LOAD_ERROR,
          fatal: !0,
          error: u
        });
      }
    }
  }
  onError(e, t) {
    t.fatal || !t.context || t.context.type === me.AUDIO_TRACK && t.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(t.context.groupId) !== -1) && this.checkRetry(t);
  }
  get allAudioTracks() {
    return this.tracks;
  }
  get audioTracks() {
    return this.tracksInGroup;
  }
  get audioTrack() {
    return this.trackId;
  }
  set audioTrack(e) {
    this.selectDefaultTrack = !1, this.setAudioTrack(e);
  }
  setAudioOption(e) {
    const t = this.hls;
    if (t.config.audioPreference = e, e) {
      const i = this.allAudioTracks;
      if (this.selectDefaultTrack = !1, i.length) {
        const s = this.currentTrack;
        if (s && Bs(e, s, Ls))
          return s;
        const n = Di(e, this.tracksInGroup, Ls);
        if (n > -1) {
          const a = this.tracksInGroup[n];
          return this.setAudioTrack(n), a;
        } else if (s) {
          let a = t.loadLevel;
          a === -1 && (a = t.firstAutoLevel);
          const o = yC(e, t.levels, i, a, Ls);
          if (o === -1)
            return null;
          t.nextLoadLevel = o;
        }
        if (e.channels || e.audioCodec) {
          const a = Di(e, i);
          if (a > -1)
            return i[a];
        }
      }
    }
    return null;
  }
  setAudioTrack(e) {
    const t = this.tracksInGroup;
    if (e < 0 || e >= t.length) {
      this.warn(`Invalid audio track id: ${e}`);
      return;
    }
    this.selectDefaultTrack = !1;
    const i = this.currentTrack, s = t[e], n = s.details && !s.details.live;
    if (e === this.trackId && s === i && n || (this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`), this.trackId = e, this.currentTrack = s, this.hls.trigger(T.AUDIO_TRACK_SWITCHING, we({}, s)), n))
      return;
    const a = this.switchParams(s.url, i == null ? void 0 : i.details, s.details);
    this.loadPlaylist(a);
  }
  findTrackId(e) {
    const t = this.tracksInGroup;
    for (let i = 0; i < t.length; i++) {
      const s = t[i];
      if (!(this.selectDefaultTrack && !s.default) && (!e || Bs(e, s, Ls)))
        return i;
    }
    if (e) {
      const {
        name: i,
        lang: s,
        assocLang: n,
        characteristics: a,
        audioCodec: o,
        channels: c
      } = e;
      for (let l = 0; l < t.length; l++) {
        const d = t[l];
        if (Bs({
          name: i,
          lang: s,
          assocLang: n,
          characteristics: a,
          audioCodec: o,
          channels: c
        }, d, Ls))
          return l;
      }
      for (let l = 0; l < t.length; l++) {
        const d = t[l];
        if (An(e.attrs, d.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"]))
          return l;
      }
      for (let l = 0; l < t.length; l++) {
        const d = t[l];
        if (An(e.attrs, d.attrs, ["LANGUAGE"]))
          return l;
      }
    }
    return -1;
  }
  loadPlaylist(e) {
    super.loadPlaylist();
    const t = this.currentTrack;
    this.shouldLoadPlaylist(t) && so(t.url, this.hls) && this.scheduleLoading(t, e);
  }
  loadingPlaylist(e, t) {
    super.loadingPlaylist(e, t);
    const i = e.id, s = e.groupId, n = this.getUrlWithDirectives(e.url, t), a = e.details, o = a == null ? void 0 : a.age;
    this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${(t == null ? void 0 : t.msn) !== void 0 ? " at sn " + t.msn + " part " + t.part : ""}${o && a.live ? " age " + o.toFixed(1) + (a.type && " " + a.type || "") : ""} ${n}`), this.hls.trigger(T.AUDIO_TRACK_LOADING, {
      url: n,
      id: i,
      groupId: s,
      deliveryDirectives: t || null,
      track: e
    });
  }
}
class cR {
  constructor(e) {
    this.tracks = void 0, this.queues = {
      video: [],
      audio: [],
      audiovideo: []
    }, this.tracks = e;
  }
  destroy() {
    this.tracks = this.queues = null;
  }
  append(e, t, i) {
    if (this.queues === null || this.tracks === null)
      return;
    const s = this.queues[t];
    s.push(e), s.length === 1 && !i && this.executeNext(t);
  }
  appendBlocker(e) {
    return new Promise((t) => {
      const i = {
        label: "async-blocker",
        execute: t,
        onStart: () => {
        },
        onComplete: () => {
        },
        onError: () => {
        }
      };
      this.append(i, e);
    });
  }
  prependBlocker(e) {
    return new Promise((t) => {
      if (this.queues) {
        const i = {
          label: "async-blocker-prepend",
          execute: t,
          onStart: () => {
          },
          onComplete: () => {
          },
          onError: () => {
          }
        };
        this.queues[e].unshift(i);
      }
    });
  }
  removeBlockers() {
    this.queues !== null && [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((e) => {
      var t;
      const i = (t = e[0]) == null ? void 0 : t.label;
      (i === "async-blocker" || i === "async-blocker-prepend") && (e[0].execute(), e.splice(0, 1));
    });
  }
  unblockAudio(e) {
    if (this.queues === null)
      return;
    this.queues.audio[0] === e && this.shiftAndExecuteNext("audio");
  }
  executeNext(e) {
    if (this.queues === null || this.tracks === null)
      return;
    const t = this.queues[e];
    if (t.length) {
      const s = t[0];
      try {
        s.execute();
      } catch (n) {
        var i;
        if (s.onError(n), this.queues === null || this.tracks === null)
          return;
        const a = (i = this.tracks[e]) == null ? void 0 : i.buffer;
        a != null && a.updating || this.shiftAndExecuteNext(e);
      }
    }
  }
  shiftAndExecuteNext(e) {
    this.queues !== null && (this.queues[e].shift(), this.executeNext(e));
  }
  current(e) {
    var t;
    return ((t = this.queues) == null ? void 0 : t[e][0]) || null;
  }
  toString() {
    const {
      queues: e,
      tracks: t
    } = this;
    return e === null || t === null ? "<destroyed>" : `
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`;
  }
  list(e) {
    var t, i;
    return (t = this.queues) != null && t[e] || (i = this.tracks) != null && i[e] ? `${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}` : "";
  }
  listSbInfo(e) {
    var t;
    const i = (t = this.tracks) == null ? void 0 : t[e], s = i == null ? void 0 : i.buffer;
    return s ? `SourceBuffer${s.updating ? " updating" : ""}${i.ended ? " ended" : ""}${i.ending ? " ending" : ""}` : "none";
  }
  listOps(e) {
    var t;
    return ((t = this.queues) == null ? void 0 : t[e].map((i) => i.label).join(", ")) || "";
  }
}
const Np = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/, G_ = "HlsJsTrackRemovedError";
class dR extends Error {
  constructor(e) {
    super(e), this.name = G_;
  }
}
class hR extends qt {
  constructor(e, t) {
    super("buffer-controller", e.logger), this.hls = void 0, this.fragmentTracker = void 0, this.details = null, this._objectUrl = null, this.operationQueue = null, this.bufferCodecEventsTotal = 0, this.media = null, this.mediaSource = null, this.lastMpegAudioChunk = null, this.blockedAudioAppend = null, this.lastVideoAppendEnd = 0, this.appendSource = void 0, this.transferData = void 0, this.overrides = void 0, this.appendErrors = {
      audio: 0,
      video: 0,
      audiovideo: 0
    }, this.tracks = {}, this.sourceBuffers = [[null, null], [null, null]], this._onEndStreaming = (i) => {
      var s;
      this.hls && ((s = this.mediaSource) == null ? void 0 : s.readyState) === "open" && this.hls.pauseBuffering();
    }, this._onStartStreaming = (i) => {
      this.hls && this.hls.resumeBuffering();
    }, this._onMediaSourceOpen = (i) => {
      const {
        media: s,
        mediaSource: n
      } = this;
      i && this.log("Media source opened"), !(!s || !n) && (n.removeEventListener("sourceopen", this._onMediaSourceOpen), s.removeEventListener("emptied", this._onMediaEmptied), this.updateDuration(), this.hls.trigger(T.MEDIA_ATTACHED, {
        media: s,
        mediaSource: n
      }), this.mediaSource !== null && this.checkPendingTracks());
    }, this._onMediaSourceClose = () => {
      this.log("Media source closed");
    }, this._onMediaSourceEnded = () => {
      this.log("Media source ended");
    }, this._onMediaEmptied = () => {
      const {
        mediaSrc: i,
        _objectUrl: s
      } = this;
      i !== s && this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`);
    }, this.hls = e, this.fragmentTracker = t, this.appendSource = M4(ys(e.config.preferManagedMediaSource)), this.initTracks(), this.registerListeners();
  }
  hasSourceTypes() {
    return Object.keys(this.tracks).length > 0;
  }
  destroy() {
    this.unregisterListeners(), this.details = null, this.lastMpegAudioChunk = this.blockedAudioAppend = null, this.transferData = this.overrides = void 0, this.operationQueue && (this.operationQueue.destroy(), this.operationQueue = null), this.hls = this.fragmentTracker = null, this._onMediaSourceOpen = this._onMediaSourceClose = null, this._onMediaSourceEnded = null, this._onStartStreaming = this._onEndStreaming = null;
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.BUFFER_RESET, this.onBufferReset, this), e.on(T.BUFFER_APPENDING, this.onBufferAppending, this), e.on(T.BUFFER_CODECS, this.onBufferCodecs, this), e.on(T.BUFFER_EOS, this.onBufferEos, this), e.on(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.on(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.on(T.FRAG_PARSED, this.onFragParsed, this), e.on(T.FRAG_CHANGED, this.onFragChanged, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.BUFFER_RESET, this.onBufferReset, this), e.off(T.BUFFER_APPENDING, this.onBufferAppending, this), e.off(T.BUFFER_CODECS, this.onBufferCodecs, this), e.off(T.BUFFER_EOS, this.onBufferEos, this), e.off(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.off(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.off(T.FRAG_PARSED, this.onFragParsed, this), e.off(T.FRAG_CHANGED, this.onFragChanged, this), e.off(T.ERROR, this.onError, this);
  }
  transferMedia() {
    const {
      media: e,
      mediaSource: t
    } = this;
    if (!e)
      return null;
    const i = {};
    if (this.operationQueue) {
      const n = this.isUpdating();
      n || this.operationQueue.removeBlockers();
      const a = this.isQueued();
      (n || a) && this.warn(`Transfering MediaSource with${a ? " operations in queue" : ""}${n ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`), this.operationQueue.destroy();
    }
    const s = this.transferData;
    return !this.sourceBufferCount && s && s.mediaSource === t ? Me(i, s.tracks) : this.sourceBuffers.forEach((n) => {
      const [a] = n;
      a && (i[a] = Me({}, this.tracks[a]), this.removeBuffer(a)), n[0] = n[1] = null;
    }), {
      media: e,
      mediaSource: t,
      tracks: i
    };
  }
  initTracks() {
    const e = {};
    this.sourceBuffers = [[null, null], [null, null]], this.tracks = e, this.resetQueue(), this.resetAppendErrors(), this.lastMpegAudioChunk = this.blockedAudioAppend = null, this.lastVideoAppendEnd = 0;
  }
  onManifestLoading() {
    this.bufferCodecEventsTotal = 0, this.details = null;
  }
  onManifestParsed(e, t) {
    var i;
    let s = 2;
    (t.audio && !t.video || !t.altAudio) && (s = 1), this.bufferCodecEventsTotal = s, this.log(`${s} bufferCodec event(s) expected.`), (i = this.transferData) != null && i.mediaSource && this.sourceBufferCount && s && this.bufferCreated();
  }
  onMediaAttaching(e, t) {
    const i = this.media = t.media;
    this.transferData = this.overrides = void 0;
    const s = ys(this.appendSource);
    if (s) {
      const n = !!t.mediaSource;
      (n || t.overrides) && (this.transferData = t, this.overrides = t.overrides);
      const a = this.mediaSource = t.mediaSource || new s();
      if (this.assignMediaSource(a), n)
        this._objectUrl = i.src, this.attachTransferred();
      else {
        const o = this._objectUrl = self.URL.createObjectURL(a);
        if (this.appendSource)
          try {
            i.removeAttribute("src");
            const c = self.ManagedMediaSource;
            i.disableRemotePlayback = i.disableRemotePlayback || c && a instanceof c, Gp(i), uR(i, o), i.load();
          } catch {
            i.src = o;
          }
        else
          i.src = o;
      }
      i.addEventListener("emptied", this._onMediaEmptied);
    }
  }
  assignMediaSource(e) {
    var t, i;
    this.log(`${((t = this.transferData) == null ? void 0 : t.mediaSource) === e ? "transferred" : "created"} media source: ${(i = e.constructor) == null ? void 0 : i.name}`), e.addEventListener("sourceopen", this._onMediaSourceOpen), e.addEventListener("sourceended", this._onMediaSourceEnded), e.addEventListener("sourceclose", this._onMediaSourceClose), this.appendSource && (e.addEventListener("startstreaming", this._onStartStreaming), e.addEventListener("endstreaming", this._onEndStreaming));
  }
  attachTransferred() {
    const e = this.media, t = this.transferData;
    if (!t || !e)
      return;
    const i = this.tracks, s = t.tracks, n = s ? Object.keys(s) : null, a = n ? n.length : 0, o = () => {
      Promise.resolve().then(() => {
        this.media && this.mediaSourceOpenOrEnded && this._onMediaSourceOpen();
      });
    };
    if (s && n && a) {
      if (!this.tracksReady) {
        this.hls.config.startFragPrefetch = !0, this.log("attachTransferred: waiting for SourceBuffer track info");
        return;
      }
      if (this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
required tracks: ${Ze(i, (c, l) => c === "initSegment" ? void 0 : l)};
transfer tracks: ${Ze(s, (c, l) => c === "initSegment" ? void 0 : l)}}`), !Ug(s, i)) {
        t.mediaSource = null, t.tracks = void 0;
        const c = e.currentTime, l = this.details, d = Math.max(c, (l == null ? void 0 : l.fragments[0].start) || 0);
        if (d - c > 1) {
          this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${d}`);
          return;
        }
        this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${c}`), this.onMediaDetaching(T.MEDIA_DETACHING, {}), this.onMediaAttaching(T.MEDIA_ATTACHING, t), e.currentTime = d;
        return;
      }
      this.transferData = void 0, n.forEach((c) => {
        const l = c, d = s[l];
        if (d) {
          const h = d.buffer;
          if (h) {
            const u = this.fragmentTracker, f = d.id;
            if (u.hasFragments(f) || u.hasParts(f)) {
              const g = ce.getBuffered(h);
              u.detectEvictedFragments(l, g, f, null, !0);
            }
            const p = I0(l), m = [l, h];
            this.sourceBuffers[p] = m, h.updating && this.operationQueue && this.operationQueue.prependBlocker(l), this.trackSourceBuffer(l, d);
          }
        }
      }), o(), this.bufferCreated();
    } else
      this.log("attachTransferred: MediaSource w/o SourceBuffers"), o();
  }
  get mediaSourceOpenOrEnded() {
    var e;
    const t = (e = this.mediaSource) == null ? void 0 : e.readyState;
    return t === "open" || t === "ended";
  }
  onMediaDetaching(e, t) {
    const i = !!t.transferMedia;
    this.transferData = this.overrides = void 0;
    const {
      media: s,
      mediaSource: n,
      _objectUrl: a
    } = this;
    if (n) {
      if (this.log(`media source ${i ? "transferring" : "detaching"}`), i)
        this.sourceBuffers.forEach(([o]) => {
          o && this.removeBuffer(o);
        }), this.resetQueue();
      else {
        if (this.mediaSourceOpenOrEnded) {
          const o = n.readyState === "open";
          try {
            const c = n.sourceBuffers;
            for (let l = c.length; l--; )
              o && c[l].abort(), n.removeSourceBuffer(c[l]);
            o && n.endOfStream();
          } catch (c) {
            this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`);
          }
        }
        this.sourceBufferCount && this.onBufferReset();
      }
      n.removeEventListener("sourceopen", this._onMediaSourceOpen), n.removeEventListener("sourceended", this._onMediaSourceEnded), n.removeEventListener("sourceclose", this._onMediaSourceClose), this.appendSource && (n.removeEventListener("startstreaming", this._onStartStreaming), n.removeEventListener("endstreaming", this._onEndStreaming)), this.mediaSource = null, this._objectUrl = null;
    }
    s && (s.removeEventListener("emptied", this._onMediaEmptied), i || (a && self.URL.revokeObjectURL(a), this.mediaSrc === a ? (s.removeAttribute("src"), this.appendSource && Gp(s), s.load()) : this.warn("media|source.src was changed by a third party - skip cleanup")), this.media = null), this.hls.trigger(T.MEDIA_DETACHED, t);
  }
  onBufferReset() {
    this.sourceBuffers.forEach(([e]) => {
      e && this.resetBuffer(e);
    }), this.initTracks();
  }
  resetBuffer(e) {
    var t;
    const i = (t = this.tracks[e]) == null ? void 0 : t.buffer;
    if (this.removeBuffer(e), i)
      try {
        var s;
        (s = this.mediaSource) != null && s.sourceBuffers.length && this.mediaSource.removeSourceBuffer(i);
      } catch (n) {
        this.warn(`onBufferReset ${e}`, n);
      }
    delete this.tracks[e];
  }
  removeBuffer(e) {
    this.removeBufferListeners(e), this.sourceBuffers[I0(e)] = [null, null];
    const t = this.tracks[e];
    t && (t.buffer = void 0);
  }
  resetQueue() {
    this.operationQueue && this.operationQueue.destroy(), this.operationQueue = new cR(this.tracks);
  }
  onBufferCodecs(e, t) {
    const i = this.tracks, s = Object.keys(t);
    this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);
    const n = "audiovideo" in t && (i.audio || i.video) || i.audiovideo && ("audio" in t || "video" in t), a = !n && this.sourceBufferCount && this.media && s.some((o) => !i[o]);
    if (n || a) {
      this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`);
      return;
    }
    s.forEach((o) => {
      var c, l;
      const d = t[o], {
        id: h,
        codec: u,
        levelCodec: f,
        container: p,
        metadata: m,
        supplemental: g
      } = d;
      let x = i[o];
      const _ = (c = this.transferData) == null || (c = c.tracks) == null ? void 0 : c[o], v = _ != null && _.buffer ? _ : x, E = (v == null ? void 0 : v.pendingCodec) || (v == null ? void 0 : v.codec), b = v == null ? void 0 : v.levelCodec;
      x || (x = i[o] = {
        buffer: void 0,
        listeners: [],
        codec: u,
        supplemental: g,
        container: p,
        levelCodec: f,
        metadata: m,
        id: h
      });
      const A = La(E, b), C = A == null ? void 0 : A.replace(Np, "$1");
      let I = La(u, f);
      const L = (l = I) == null ? void 0 : l.replace(Np, "$1");
      I && A && C !== L && (o.slice(0, 5) === "audio" && (I = to(I, this.appendSource)), this.log(`switching codec ${E} to ${I}`), I !== (x.pendingCodec || x.codec) && (x.pendingCodec = I), x.container = p, this.appendChangeType(o, p, I));
    }), (this.tracksReady || this.sourceBufferCount) && (t.tracks = this.sourceBufferTracks), !this.sourceBufferCount && this.mediaSourceOpenOrEnded && this.checkPendingTracks();
  }
  get sourceBufferTracks() {
    return Object.keys(this.tracks).reduce((e, t) => {
      const i = this.tracks[t];
      return e[t] = {
        id: i.id,
        container: i.container,
        codec: i.codec,
        levelCodec: i.levelCodec
      }, e;
    }, {});
  }
  appendChangeType(e, t, i) {
    const s = `${t};codecs=${i}`, n = {
      label: `change-type=${s}`,
      execute: () => {
        const a = this.tracks[e];
        if (a) {
          const o = a.buffer;
          o != null && o.changeType && (this.log(`changing ${e} sourceBuffer type to ${s}`), o.changeType(s), a.codec = i, a.container = t);
        }
        this.shiftAndExecuteNext(e);
      },
      onStart: () => {
      },
      onComplete: () => {
      },
      onError: (a) => {
        this.warn(`Failed to change ${e} SourceBuffer type`, a);
      }
    };
    this.append(n, e, this.isPending(this.tracks[e]));
  }
  blockAudio(e) {
    var t;
    const i = e.start, s = i + e.duration * 0.05;
    if (((t = this.fragmentTracker.getAppendedFrag(i, te.MAIN)) == null ? void 0 : t.gap) === !0)
      return;
    const a = {
      label: "block-audio",
      execute: () => {
        var o;
        const c = this.tracks.video;
        (this.lastVideoAppendEnd > s || c != null && c.buffer && ce.isBuffered(c.buffer, s) || ((o = this.fragmentTracker.getAppendedFrag(s, te.MAIN)) == null ? void 0 : o.gap) === !0) && (this.blockedAudioAppend = null, this.shiftAndExecuteNext("audio"));
      },
      onStart: () => {
      },
      onComplete: () => {
      },
      onError: (o) => {
        this.warn("Error executing block-audio operation", o);
      }
    };
    this.blockedAudioAppend = {
      op: a,
      frag: e
    }, this.append(a, "audio", !0);
  }
  unblockAudio() {
    const {
      blockedAudioAppend: e,
      operationQueue: t
    } = this;
    e && t && (this.blockedAudioAppend = null, t.unblockAudio(e.op));
  }
  onBufferAppending(e, t) {
    const {
      tracks: i
    } = this, {
      data: s,
      type: n,
      parent: a,
      frag: o,
      part: c,
      chunkMeta: l,
      offset: d
    } = t, h = l.buffering[n], {
      sn: u,
      cc: f
    } = o, p = self.performance.now();
    h.start = p;
    const m = o.stats.buffering, g = c ? c.stats.buffering : null;
    m.start === 0 && (m.start = p), g && g.start === 0 && (g.start = p);
    const x = i.audio;
    let _ = !1;
    n === "audio" && (x == null ? void 0 : x.container) === "audio/mpeg" && (_ = !this.lastMpegAudioChunk || l.id === 1 || this.lastMpegAudioChunk.sn !== l.sn, this.lastMpegAudioChunk = l);
    const v = i.video, E = v == null ? void 0 : v.buffer;
    if (E && u !== "initSegment") {
      const C = c || o, I = this.blockedAudioAppend;
      if (n === "audio" && a !== "main" && !this.blockedAudioAppend && !(v.ending || v.ended)) {
        const R = C.start + C.duration * 0.05, D = E.buffered, M = this.currentOp("video");
        !D.length && !M ? this.blockAudio(C) : !M && !ce.isBuffered(E, R) && this.lastVideoAppendEnd < R && this.blockAudio(C);
      } else if (n === "video") {
        const L = C.end;
        if (I) {
          const R = I.frag.start;
          (L > R || L < this.lastVideoAppendEnd || ce.isBuffered(E, R)) && this.unblockAudio();
        }
        this.lastVideoAppendEnd = L;
      }
    }
    const b = (c || o).start, A = {
      label: `append-${n}`,
      execute: () => {
        var C;
        h.executeStart = self.performance.now();
        const I = (C = this.tracks[n]) == null ? void 0 : C.buffer;
        I && (_ ? this.updateTimestampOffset(I, b, 0.1, n, u, f) : d !== void 0 && q(d) && this.updateTimestampOffset(I, d, 1e-6, n, u, f)), this.appendExecutor(s, n);
      },
      onStart: () => {
      },
      onComplete: () => {
        const C = self.performance.now();
        h.executeEnd = h.end = C, m.first === 0 && (m.first = C), g && g.first === 0 && (g.first = C);
        const I = {};
        this.sourceBuffers.forEach(([L, R]) => {
          L && (I[L] = ce.getBuffered(R));
        }), this.appendErrors[n] = 0, n === "audio" || n === "video" ? this.appendErrors.audiovideo = 0 : (this.appendErrors.audio = 0, this.appendErrors.video = 0), this.hls.trigger(T.BUFFER_APPENDED, {
          type: n,
          frag: o,
          part: c,
          chunkMeta: l,
          parent: o.type,
          timeRanges: I
        });
      },
      onError: (C) => {
        var I;
        const L = {
          type: ie.MEDIA_ERROR,
          parent: o.type,
          details: V.BUFFER_APPEND_ERROR,
          sourceBufferName: n,
          frag: o,
          part: c,
          chunkMeta: l,
          error: C,
          err: C,
          fatal: !1
        }, R = (I = this.media) == null ? void 0 : I.error;
        if (C.code === DOMException.QUOTA_EXCEEDED_ERR || C.name == "QuotaExceededError" || "quota" in C)
          L.details = V.BUFFER_FULL_ERROR;
        else if (C.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !R)
          L.errorAction = Tr(!0);
        else if (C.name === G_ && this.sourceBufferCount === 0)
          L.errorAction = Tr(!0);
        else {
          const D = ++this.appendErrors[n];
          this.warn(`Failed ${D}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${R || "no media error"})`), (D >= this.hls.config.appendErrorMaxRetry || R) && (L.fatal = !0);
        }
        this.hls.trigger(T.ERROR, L);
      }
    };
    this.append(A, n, this.isPending(this.tracks[n]));
  }
  getFlushOp(e, t, i) {
    return this.log(`queuing "${e}" remove ${t}-${i}`), {
      label: "remove",
      execute: () => {
        this.removeExecutor(e, t, i);
      },
      onStart: () => {
      },
      onComplete: () => {
        this.hls.trigger(T.BUFFER_FLUSHED, {
          type: e
        });
      },
      onError: (s) => {
        this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`, s);
      }
    };
  }
  onBufferFlushing(e, t) {
    const {
      type: i,
      startOffset: s,
      endOffset: n
    } = t;
    i ? this.append(this.getFlushOp(i, s, n), i) : this.sourceBuffers.forEach(([a]) => {
      a && this.append(this.getFlushOp(a, s, n), a);
    });
  }
  onFragParsed(e, t) {
    const {
      frag: i,
      part: s
    } = t, n = [], a = s ? s.elementaryStreams : i.elementaryStreams;
    a[Oe.AUDIOVIDEO] ? n.push("audiovideo") : (a[Oe.AUDIO] && n.push("audio"), a[Oe.VIDEO] && n.push("video"));
    const o = () => {
      const c = self.performance.now();
      i.stats.buffering.end = c, s && (s.stats.buffering.end = c);
      const l = s ? s.stats : i.stats;
      this.hls.trigger(T.FRAG_BUFFERED, {
        frag: i,
        part: s,
        stats: l,
        id: i.type
      });
    };
    n.length === 0 && this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`), this.blockBuffers(o, n).catch((c) => {
      this.warn(`Fragment buffered callback ${c}`), this.stepOperationQueue(this.sourceBufferTypes);
    });
  }
  onFragChanged(e, t) {
    this.trimBuffers();
  }
  get bufferedToEnd() {
    return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([e]) => {
      if (e) {
        const t = this.tracks[e];
        if (t)
          return !t.ended || t.ending;
      }
      return !1;
    });
  }
  // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  // an undefined data.type will mark all buffers as EOS.
  onBufferEos(e, t) {
    var i;
    this.sourceBuffers.forEach(([a]) => {
      if (a) {
        const o = this.tracks[a];
        (!t.type || t.type === a) && (o.ending = !0, o.ended || (o.ended = !0, this.log(`${a} buffer reached EOS`)));
      }
    });
    const s = ((i = this.overrides) == null ? void 0 : i.endOfStream) !== !1;
    this.sourceBufferCount > 0 && !this.sourceBuffers.some(([a]) => {
      var o;
      return a && !((o = this.tracks[a]) != null && o.ended);
    }) ? s ? (this.log("Queueing EOS"), this.blockUntilOpen(() => {
      this.tracksEnded();
      const {
        mediaSource: a
      } = this;
      if (!a || a.readyState !== "open") {
        a && this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);
        return;
      }
      this.log("Calling mediaSource.endOfStream()"), a.endOfStream(), this.hls.trigger(T.BUFFERED_TO_END, void 0);
    })) : (this.tracksEnded(), this.hls.trigger(T.BUFFERED_TO_END, void 0)) : t.type === "video" && this.unblockAudio();
  }
  tracksEnded() {
    this.sourceBuffers.forEach(([e]) => {
      if (e !== null) {
        const t = this.tracks[e];
        t && (t.ending = !1);
      }
    });
  }
  onLevelUpdated(e, {
    details: t
  }) {
    t.fragments.length && (this.details = t, this.updateDuration());
  }
  updateDuration() {
    this.blockUntilOpen(() => {
      const e = this.getDurationAndRange();
      e && this.updateMediaSource(e);
    });
  }
  onError(e, t) {
    if (t.details === V.BUFFER_APPEND_ERROR && t.frag) {
      var i;
      const s = (i = t.errorAction) == null ? void 0 : i.nextAutoLevel;
      q(s) && s !== t.frag.level && this.resetAppendErrors();
    }
  }
  resetAppendErrors() {
    this.appendErrors = {
      audio: 0,
      video: 0,
      audiovideo: 0
    };
  }
  trimBuffers() {
    const {
      hls: e,
      details: t,
      media: i
    } = this;
    if (!i || t === null || !this.sourceBufferCount)
      return;
    const s = e.config, n = i.currentTime, a = t.levelTargetDuration, o = t.live && s.liveBackBufferLength !== null ? s.liveBackBufferLength : s.backBufferLength;
    if (q(o) && o >= 0) {
      const l = Math.max(o, a), d = Math.floor(n / a) * a - l;
      this.flushBackBuffer(n, a, d);
    }
    const c = s.frontBufferFlushThreshold;
    if (q(c) && c > 0) {
      const l = Math.max(s.maxBufferLength, c), d = Math.max(l, a), h = Math.floor(n / a) * a + d;
      this.flushFrontBuffer(n, a, h);
    }
  }
  flushBackBuffer(e, t, i) {
    this.sourceBuffers.forEach(([s, n]) => {
      if (n) {
        const o = ce.getBuffered(n);
        if (o.length > 0 && i > o.start(0)) {
          var a;
          this.hls.trigger(T.BACK_BUFFER_REACHED, {
            bufferEnd: i
          });
          const c = this.tracks[s];
          if ((a = this.details) != null && a.live)
            this.hls.trigger(T.LIVE_BACK_BUFFER_REACHED, {
              bufferEnd: i
            });
          else if (c != null && c.ended) {
            this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);
            return;
          }
          this.hls.trigger(T.BUFFER_FLUSHING, {
            startOffset: 0,
            endOffset: i,
            type: s
          });
        }
      }
    });
  }
  flushFrontBuffer(e, t, i) {
    this.sourceBuffers.forEach(([s, n]) => {
      if (n) {
        const a = ce.getBuffered(n), o = a.length;
        if (o < 2)
          return;
        const c = a.start(o - 1), l = a.end(o - 1);
        if (i > c || e >= c && e <= l)
          return;
        this.hls.trigger(T.BUFFER_FLUSHING, {
          startOffset: c,
          endOffset: 1 / 0,
          type: s
        });
      }
    });
  }
  /**
   * Update Media Source duration to current level duration or override to Infinity if configuration parameter
   * 'liveDurationInfinity` is set to `true`
   * More details: https://github.com/video-dev/hls.js/issues/355
   */
  getDurationAndRange() {
    var e;
    const {
      details: t,
      mediaSource: i
    } = this;
    if (!t || !this.media || (i == null ? void 0 : i.readyState) !== "open")
      return null;
    const s = t.edge;
    if (t.live && this.hls.config.liveDurationInfinity) {
      if (t.fragments.length && i.setLiveSeekableRange) {
        const l = Math.max(0, t.fragmentStart), d = Math.max(l, s);
        return {
          duration: 1 / 0,
          start: l,
          end: d
        };
      }
      return {
        duration: 1 / 0
      };
    }
    const n = (e = this.overrides) == null ? void 0 : e.duration;
    if (n)
      return q(n) ? {
        duration: n
      } : null;
    const a = this.media.duration, o = q(i.duration) ? i.duration : 0;
    return s > o && s > a || !q(a) ? {
      duration: s
    } : null;
  }
  updateMediaSource({
    duration: e,
    start: t,
    end: i
  }) {
    const s = this.mediaSource;
    !this.media || !s || s.readyState !== "open" || (s.duration !== e && (q(e) && this.log(`Updating MediaSource duration to ${e.toFixed(3)}`), s.duration = e), t !== void 0 && i !== void 0 && (this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`), s.setLiveSeekableRange(t, i)));
  }
  get tracksReady() {
    const e = this.pendingTrackCount;
    return e > 0 && (e >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  }
  checkPendingTracks() {
    const {
      bufferCodecEventsTotal: e,
      pendingTrackCount: t,
      tracks: i
    } = this;
    if (this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ze(i)}`), this.tracksReady) {
      var s;
      const n = (s = this.transferData) == null ? void 0 : s.tracks;
      n && Object.keys(n).length ? this.attachTransferred() : this.createSourceBuffers();
    }
  }
  bufferCreated() {
    if (this.sourceBufferCount) {
      const e = {};
      this.sourceBuffers.forEach(([t, i]) => {
        if (t) {
          const s = this.tracks[t];
          e[t] = {
            buffer: i,
            container: s.container,
            codec: s.codec,
            supplemental: s.supplemental,
            levelCodec: s.levelCodec,
            id: s.id,
            metadata: s.metadata
          };
        }
      }), this.hls.trigger(T.BUFFER_CREATED, {
        tracks: e
      }), this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`), this.sourceBuffers.forEach(([t]) => {
        this.executeNext(t);
      });
    } else {
      const e = new Error("could not create source buffer for media codec(s)");
      this.hls.trigger(T.ERROR, {
        type: ie.MEDIA_ERROR,
        details: V.BUFFER_INCOMPATIBLE_CODECS_ERROR,
        fatal: !0,
        error: e,
        reason: e.message
      });
    }
  }
  createSourceBuffers() {
    const {
      tracks: e,
      sourceBuffers: t,
      mediaSource: i
    } = this;
    if (!i)
      throw new Error("createSourceBuffers called when mediaSource was null");
    for (const n in e) {
      const a = n, o = e[a];
      if (this.isPending(o)) {
        const c = this.getTrackCodec(o, a), l = `${o.container};codecs=${c}`;
        o.codec = c, this.log(`creating sourceBuffer(${l})${this.currentOp(a) ? " Queued" : ""} ${Ze(o)}`);
        try {
          const d = i.addSourceBuffer(l), h = I0(a), u = [a, d];
          t[h] = u, o.buffer = d;
        } catch (d) {
          var s;
          this.error(`error while trying to add sourceBuffer: ${d.message}`), this.shiftAndExecuteNext(a), (s = this.operationQueue) == null || s.removeBlockers(), delete this.tracks[a], this.hls.trigger(T.ERROR, {
            type: ie.MEDIA_ERROR,
            details: V.BUFFER_ADD_CODEC_ERROR,
            fatal: !1,
            error: d,
            sourceBufferName: a,
            mimeType: l,
            parent: o.id
          });
          return;
        }
        this.trackSourceBuffer(a, o);
      }
    }
    this.bufferCreated();
  }
  getTrackCodec(e, t) {
    const i = e.supplemental;
    let s = e.codec;
    i && (t === "video" || t === "audiovideo") && Lc(i, "video") && (s = q4(s, i));
    const n = La(s, e.levelCodec);
    return n ? t.slice(0, 5) === "audio" ? to(n, this.appendSource) : n : "";
  }
  trackSourceBuffer(e, t) {
    const i = t.buffer;
    if (!i)
      return;
    const s = this.getTrackCodec(t, e);
    this.tracks[e] = {
      buffer: i,
      codec: s,
      container: t.container,
      levelCodec: t.levelCodec,
      supplemental: t.supplemental,
      metadata: t.metadata,
      id: t.id,
      listeners: []
    }, this.removeBufferListeners(e), this.addBufferListener(e, "updatestart", this.onSBUpdateStart), this.addBufferListener(e, "updateend", this.onSBUpdateEnd), this.addBufferListener(e, "error", this.onSBUpdateError), this.appendSource && this.addBufferListener(e, "bufferedchange", (n, a) => {
      const o = a.removedRanges;
      o != null && o.length && this.hls.trigger(T.BUFFER_FLUSHED, {
        type: n
      });
    });
  }
  get mediaSrc() {
    var e, t;
    const i = ((e = this.media) == null || (t = e.querySelector) == null ? void 0 : t.call(e, "source")) || this.media;
    return i == null ? void 0 : i.src;
  }
  onSBUpdateStart(e) {
    const t = this.currentOp(e);
    t && t.onStart();
  }
  onSBUpdateEnd(e) {
    var t;
    if (((t = this.mediaSource) == null ? void 0 : t.readyState) === "closed") {
      this.resetBuffer(e);
      return;
    }
    const i = this.currentOp(e);
    i && (i.onComplete(), this.shiftAndExecuteNext(e));
  }
  onSBUpdateError(e, t) {
    var i;
    const s = new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i = this.mediaSource) == null ? void 0 : i.readyState}`);
    this.error(`${s}`, t), this.hls.trigger(T.ERROR, {
      type: ie.MEDIA_ERROR,
      details: V.BUFFER_APPENDING_ERROR,
      sourceBufferName: e,
      error: s,
      fatal: !1
    });
    const n = this.currentOp(e);
    n && n.onError(s);
  }
  updateTimestampOffset(e, t, i, s, n, a) {
    const o = t - e.timestampOffset;
    Math.abs(o) >= i && (this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`), e.timestampOffset = t);
  }
  // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  removeExecutor(e, t, i) {
    const {
      media: s,
      mediaSource: n
    } = this, a = this.tracks[e], o = a == null ? void 0 : a.buffer;
    if (!s || !n || !o) {
      this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`), this.shiftAndExecuteNext(e);
      return;
    }
    const c = q(s.duration) ? s.duration : 1 / 0, l = q(n.duration) ? n.duration : 1 / 0, d = Math.max(0, t), h = Math.min(i, c, l);
    h > d && (!a.ending || a.ended) ? (a.ended = !1, this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`), o.remove(d, h)) : this.shiftAndExecuteNext(e);
  }
  // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  appendExecutor(e, t) {
    const i = this.tracks[t], s = i == null ? void 0 : i.buffer;
    if (!s)
      throw new dR(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);
    i.ending = !1, i.ended = !1, s.appendBuffer(e);
  }
  blockUntilOpen(e) {
    if (this.isUpdating() || this.isQueued())
      this.blockBuffers(e).catch((t) => {
        this.warn(`SourceBuffer blocked callback ${t}`), this.stepOperationQueue(this.sourceBufferTypes);
      });
    else
      try {
        e();
      } catch (t) {
        this.warn(`Callback run without blocking ${this.operationQueue} ${t}`);
      }
  }
  isUpdating() {
    return this.sourceBuffers.some(([e, t]) => e && t.updating);
  }
  isQueued() {
    return this.sourceBuffers.some(([e]) => e && !!this.currentOp(e));
  }
  isPending(e) {
    return !!e && !e.buffer;
  }
  // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  // upon completion, since we already do it here
  blockBuffers(e, t = this.sourceBufferTypes) {
    if (!t.length)
      return this.log("Blocking operation requested, but no SourceBuffers exist"), Promise.resolve().then(e);
    const {
      operationQueue: i
    } = this, s = t.map((a) => this.appendBlocker(a));
    return t.length > 1 && !!this.blockedAudioAppend && this.unblockAudio(), Promise.all(s).then((a) => {
      i === this.operationQueue && (e(), this.stepOperationQueue(this.sourceBufferTypes));
    });
  }
  stepOperationQueue(e) {
    e.forEach((t) => {
      var i;
      const s = (i = this.tracks[t]) == null ? void 0 : i.buffer;
      !s || s.updating || this.shiftAndExecuteNext(t);
    });
  }
  append(e, t, i) {
    this.operationQueue && this.operationQueue.append(e, t, i);
  }
  appendBlocker(e) {
    if (this.operationQueue)
      return this.operationQueue.appendBlocker(e);
  }
  currentOp(e) {
    return this.operationQueue ? this.operationQueue.current(e) : null;
  }
  executeNext(e) {
    e && this.operationQueue && this.operationQueue.executeNext(e);
  }
  shiftAndExecuteNext(e) {
    this.operationQueue && this.operationQueue.shiftAndExecuteNext(e);
  }
  get pendingTrackCount() {
    return Object.keys(this.tracks).reduce((e, t) => e + (this.isPending(this.tracks[t]) ? 1 : 0), 0);
  }
  get sourceBufferCount() {
    return this.sourceBuffers.reduce((e, [t]) => e + (t ? 1 : 0), 0);
  }
  get sourceBufferTypes() {
    return this.sourceBuffers.map(([e]) => e).filter((e) => !!e);
  }
  addBufferListener(e, t, i) {
    const s = this.tracks[e];
    if (!s)
      return;
    const n = s.buffer;
    if (!n)
      return;
    const a = i.bind(this, e);
    s.listeners.push({
      event: t,
      listener: a
    }), n.addEventListener(t, a);
  }
  removeBufferListeners(e) {
    const t = this.tracks[e];
    if (!t)
      return;
    const i = t.buffer;
    i && (t.listeners.forEach((s) => {
      i.removeEventListener(s.event, s.listener);
    }), t.listeners.length = 0);
  }
}
function Gp(r) {
  const e = r.querySelectorAll("source");
  [].slice.call(e).forEach((t) => {
    r.removeChild(t);
  });
}
function uR(r, e) {
  const t = self.document.createElement("source");
  t.type = "video/mp4", t.src = e, r.appendChild(t);
}
function I0(r) {
  return r === "audio" ? 1 : 0;
}
class sh {
  constructor(e) {
    this.hls = void 0, this.autoLevelCapping = void 0, this.firstLevel = void 0, this.media = void 0, this.restrictedLevels = void 0, this.timer = void 0, this.clientRect = void 0, this.streamController = void 0, this.hls = e, this.autoLevelCapping = Number.POSITIVE_INFINITY, this.firstLevel = -1, this.media = null, this.restrictedLevels = [], this.timer = void 0, this.clientRect = null, this.registerListeners();
  }
  setStreamController(e) {
    this.streamController = e;
  }
  destroy() {
    this.hls && this.unregisterListener(), this.timer && this.stopCapping(), this.media = null, this.clientRect = null, this.hls = this.streamController = null;
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this), e.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.on(T.BUFFER_CODECS, this.onBufferCodecs, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListener() {
    const {
      hls: e
    } = this;
    e.off(T.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this), e.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.off(T.BUFFER_CODECS, this.onBufferCodecs, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  onFpsDropLevelCapping(e, t) {
    const i = this.hls.levels[t.droppedLevel];
    this.isLevelAllowed(i) && this.restrictedLevels.push({
      bitrate: i.bitrate,
      height: i.height,
      width: i.width
    });
  }
  onMediaAttaching(e, t) {
    this.media = t.media instanceof HTMLVideoElement ? t.media : null, this.clientRect = null, this.timer && this.hls.levels.length && this.detectPlayerSize();
  }
  onManifestParsed(e, t) {
    const i = this.hls;
    this.restrictedLevels = [], this.firstLevel = t.firstLevel, i.config.capLevelToPlayerSize && t.video && this.startCapping();
  }
  onLevelsUpdated(e, t) {
    this.timer && q(this.autoLevelCapping) && this.detectPlayerSize();
  }
  // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  // to the first level
  onBufferCodecs(e, t) {
    this.hls.config.capLevelToPlayerSize && t.video && this.startCapping();
  }
  onMediaDetaching() {
    this.stopCapping(), this.media = null;
  }
  detectPlayerSize() {
    if (this.media) {
      if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
        this.clientRect = null;
        return;
      }
      const e = this.hls.levels;
      if (e.length) {
        const t = this.hls, i = this.getMaxLevel(e.length - 1);
        i !== this.autoLevelCapping && t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`), t.autoLevelCapping = i, t.autoLevelEnabled && t.autoLevelCapping > this.autoLevelCapping && this.streamController && this.streamController.nextLevelSwitch(), this.autoLevelCapping = t.autoLevelCapping;
      }
    }
  }
  /*
   * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
   */
  getMaxLevel(e) {
    const t = this.hls.levels;
    if (!t.length)
      return -1;
    const i = t.filter((s, n) => this.isLevelAllowed(s) && n <= e);
    return this.clientRect = null, sh.getMaxLevelByMediaSize(i, this.mediaWidth, this.mediaHeight);
  }
  startCapping() {
    this.timer || (this.autoLevelCapping = Number.POSITIVE_INFINITY, self.clearInterval(this.timer), this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1e3), this.detectPlayerSize());
  }
  stopCapping() {
    this.restrictedLevels = [], this.firstLevel = -1, this.autoLevelCapping = Number.POSITIVE_INFINITY, this.timer && (self.clearInterval(this.timer), this.timer = void 0);
  }
  getDimensions() {
    if (this.clientRect)
      return this.clientRect;
    const e = this.media, t = {
      width: 0,
      height: 0
    };
    if (e) {
      const i = e.getBoundingClientRect();
      t.width = i.width, t.height = i.height, !t.width && !t.height && (t.width = i.right - i.left || e.width || 0, t.height = i.bottom - i.top || e.height || 0);
    }
    return this.clientRect = t, t;
  }
  get mediaWidth() {
    return this.getDimensions().width * this.contentScaleFactor;
  }
  get mediaHeight() {
    return this.getDimensions().height * this.contentScaleFactor;
  }
  get contentScaleFactor() {
    let e = 1;
    if (!this.hls.config.ignoreDevicePixelRatio)
      try {
        e = self.devicePixelRatio;
      } catch {
      }
    return Math.min(e, this.hls.config.maxDevicePixelRatio);
  }
  isLevelAllowed(e) {
    return !this.restrictedLevels.some((i) => e.bitrate === i.bitrate && e.width === i.width && e.height === i.height);
  }
  static getMaxLevelByMediaSize(e, t, i) {
    if (!(e != null && e.length))
      return -1;
    const s = (o, c) => c ? o.width !== c.width || o.height !== c.height : !0;
    let n = e.length - 1;
    const a = Math.max(t, i);
    for (let o = 0; o < e.length; o += 1) {
      const c = e[o];
      if ((c.width >= a || c.height >= a) && s(c, e[o + 1])) {
        n = o;
        break;
      }
    }
    return n;
  }
}
const fR = {
  /**
   * text file, such as a manifest or playlist
   */
  MANIFEST: "m",
  /**
   * audio only
   */
  AUDIO: "a",
  /**
   * video only
   */
  VIDEO: "v",
  /**
   * muxed audio and video
   */
  MUXED: "av",
  /**
   * init segment
   */
  INIT: "i",
  /**
   * caption or subtitle
   */
  CAPTION: "c",
  /**
   * ISOBMFF timed text track
   */
  TIMED_TEXT: "tt",
  /**
   * cryptographic key, license or certificate.
   */
  KEY: "k",
  /**
   * other
   */
  OTHER: "o"
}, It = fR, pR = {
  /**
   * HTTP Live Streaming (HLS)
   */
  HLS: "h"
}, mR = pR;
class Mi {
  constructor(e, t) {
    Array.isArray(e) && (e = e.map((i) => i instanceof Mi ? i : new Mi(i))), this.value = e, this.params = t;
  }
}
const gR = "Dict";
function _R(r) {
  return Array.isArray(r) ? JSON.stringify(r) : r instanceof Map ? "Map{}" : r instanceof Set ? "Set{}" : typeof r == "object" ? JSON.stringify(r) : String(r);
}
function yR(r, e, t, i) {
  return new Error(`failed to ${r} "${_R(e)}" as ${t}`, {
    cause: i
  });
}
function Bi(r, e, t) {
  return yR("serialize", r, e, t);
}
class U_ {
  constructor(e) {
    this.description = e;
  }
}
const Up = "Bare Item", xR = "Boolean";
function vR(r) {
  if (typeof r != "boolean")
    throw Bi(r, xR);
  return r ? "?1" : "?0";
}
function ER(r) {
  return btoa(String.fromCharCode(...r));
}
const SR = "Byte Sequence";
function TR(r) {
  if (ArrayBuffer.isView(r) === !1)
    throw Bi(r, SR);
  return `:${ER(r)}:`;
}
const bR = "Integer";
function AR(r) {
  return r < -999999999999999 || 999999999999999 < r;
}
function V_(r) {
  if (AR(r))
    throw Bi(r, bR);
  return r.toString();
}
function CR(r) {
  return `@${V_(r.getTime() / 1e3)}`;
}
function W_(r, e) {
  if (r < 0)
    return -W_(-r, e);
  const t = Math.pow(10, e);
  if (Math.abs(r * t % 1 - 0.5) < Number.EPSILON) {
    const s = Math.floor(r * t);
    return (s % 2 === 0 ? s : s + 1) / t;
  } else
    return Math.round(r * t) / t;
}
const RR = "Decimal";
function IR(r) {
  const e = W_(r, 3);
  if (Math.floor(Math.abs(e)).toString().length > 12)
    throw Bi(r, RR);
  const t = e.toString();
  return t.includes(".") ? t : `${t}.0`;
}
const LR = "String", DR = /[\x00-\x1f\x7f]+/;
function PR(r) {
  if (DR.test(r))
    throw Bi(r, LR);
  return `"${r.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function kR(r) {
  return r.description || r.toString().slice(7, -1);
}
const wR = "Token";
function Vp(r) {
  const e = kR(r);
  if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e) === !1)
    throw Bi(e, wR);
  return e;
}
function Uc(r) {
  switch (typeof r) {
    case "number":
      if (!q(r))
        throw Bi(r, Up);
      return Number.isInteger(r) ? V_(r) : IR(r);
    case "string":
      return PR(r);
    case "symbol":
      return Vp(r);
    case "boolean":
      return vR(r);
    case "object":
      if (r instanceof Date)
        return CR(r);
      if (r instanceof Uint8Array)
        return TR(r);
      if (r instanceof U_)
        return Vp(r);
    default:
      throw Bi(r, Up);
  }
}
const MR = "Key";
function Vc(r) {
  if (/^[a-z*][a-z0-9\-_.*]*$/.test(r) === !1)
    throw Bi(r, MR);
  return r;
}
function rh(r) {
  return r == null ? "" : Object.entries(r).map(([e, t]) => t === !0 ? `;${Vc(e)}` : `;${Vc(e)}=${Uc(t)}`).join("");
}
function H_(r) {
  return r instanceof Mi ? `${Uc(r.value)}${rh(r.params)}` : Uc(r);
}
function BR(r) {
  return `(${r.value.map(H_).join(" ")})${rh(r.params)}`;
}
function FR(r, e = {
  whitespace: !0
}) {
  if (typeof r != "object" || r == null)
    throw Bi(r, gR);
  const t = r instanceof Map ? r.entries() : Object.entries(r), i = e != null && e.whitespace ? " " : "";
  return Array.from(t).map(([s, n]) => {
    n instanceof Mi || (n = new Mi(n));
    let a = Vc(s);
    return n.value === !0 ? a += rh(n.params) : (a += "=", Array.isArray(n.value) ? a += BR(n) : a += H_(n)), a;
  }).join(`,${i}`);
}
function Z_(r, e) {
  return FR(r, e);
}
const vi = "CMCD-Object", Ye = "CMCD-Request", As = "CMCD-Session", rs = "CMCD-Status", OR = {
  // Object
  br: vi,
  ab: vi,
  d: vi,
  ot: vi,
  tb: vi,
  tpb: vi,
  lb: vi,
  tab: vi,
  lab: vi,
  url: vi,
  // Request
  pb: Ye,
  bl: Ye,
  tbl: Ye,
  dl: Ye,
  ltc: Ye,
  mtp: Ye,
  nor: Ye,
  nrr: Ye,
  rc: Ye,
  sn: Ye,
  sta: Ye,
  su: Ye,
  ttfb: Ye,
  ttfbb: Ye,
  ttlb: Ye,
  cmsdd: Ye,
  cmsds: Ye,
  smrt: Ye,
  df: Ye,
  cs: Ye,
  // TODO: Which header to put the `ts` field is not defined yet.
  ts: Ye,
  // Session
  cid: As,
  pr: As,
  sf: As,
  sid: As,
  st: As,
  v: As,
  msd: As,
  // Status
  bs: rs,
  bsd: rs,
  cdn: rs,
  rtp: rs,
  bg: rs,
  pt: rs,
  ec: rs,
  e: rs
}, NR = {
  /**
   * keys whose values vary with each request.
   */
  REQUEST: Ye
};
function GR(r) {
  return Object.keys(r).reduce((e, t) => {
    var i;
    return (i = r[t]) === null || i === void 0 || i.forEach((s) => e[s] = t), e;
  }, {});
}
function UR(r, e) {
  const t = {};
  if (!r)
    return t;
  const i = Object.keys(r), s = e ? GR(e) : {};
  return i.reduce((n, a) => {
    var o;
    const c = OR[a] || s[a] || NR.REQUEST, l = (o = n[c]) !== null && o !== void 0 ? o : n[c] = {};
    return l[a] = r[a], n;
  }, t);
}
function VR(r) {
  return ["ot", "sf", "st", "e", "sta"].includes(r);
}
function WR(r) {
  return typeof r == "number" ? q(r) : r != null && r !== "" && r !== !1;
}
const $_ = "event";
function HR(r, e) {
  const t = new URL(r), i = new URL(e);
  if (t.origin !== i.origin)
    return r;
  const s = t.pathname.split("/").slice(1), n = i.pathname.split("/").slice(1, -1);
  for (; s[0] === n[0]; )
    s.shift(), n.shift();
  for (; n.length; )
    n.shift(), s.unshift("..");
  return s.join("/") + t.search + t.hash;
}
const Ma = (r) => Math.round(r), Wc = (r, e) => Array.isArray(r) ? r.map((t) => Wc(t, e)) : r instanceof Mi && typeof r.value == "string" ? new Mi(Wc(r.value, e), r.params) : (e.baseUrl && (r = HR(r, e.baseUrl)), e.version === 1 ? encodeURIComponent(r) : r), sa = (r) => Ma(r / 100) * 100, ZR = (r, e) => {
  let t = r;
  return e.version >= 2 && (r instanceof Mi && typeof r.value == "string" ? t = new Mi([r]) : typeof r == "string" && (t = [r])), Wc(t, e);
}, $R = {
  /**
   * Bitrate (kbps) rounded integer
   */
  br: Ma,
  /**
   * Duration (milliseconds) rounded integer
   */
  d: Ma,
  /**
   * Buffer Length (milliseconds) rounded nearest 100ms
   */
  bl: sa,
  /**
   * Deadline (milliseconds) rounded nearest 100ms
   */
  dl: sa,
  /**
   * Measured Throughput (kbps) rounded nearest 100kbps
   */
  mtp: sa,
  /**
   * Next Object Request URL encoded
   */
  nor: ZR,
  /**
   * Requested maximum throughput (kbps) rounded nearest 100kbps
   */
  rtp: sa,
  /**
   * Top Bitrate (kbps) rounded integer
   */
  tb: Ma
}, K_ = "request", X_ = "response", nh = ["ab", "bg", "bl", "br", "bs", "bsd", "cdn", "cid", "cs", "df", "ec", "lab", "lb", "ltc", "msd", "mtp", "pb", "pr", "pt", "sf", "sid", "sn", "st", "sta", "tab", "tb", "tbl", "tpb", "ts", "v"], KR = ["e"], XR = /^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;
function Do(r) {
  return XR.test(r);
}
function YR(r) {
  return nh.includes(r) || KR.includes(r) || Do(r);
}
const Y_ = ["d", "dl", "nor", "ot", "rtp", "su"];
function zR(r) {
  return nh.includes(r) || Y_.includes(r) || Do(r);
}
const jR = ["cmsdd", "cmsds", "rc", "smrt", "ttfb", "ttfbb", "ttlb", "url"];
function QR(r) {
  return nh.includes(r) || Y_.includes(r) || jR.includes(r) || Do(r);
}
const JR = ["bl", "br", "bs", "cid", "d", "dl", "mtp", "nor", "nrr", "ot", "pr", "rtp", "sf", "sid", "st", "su", "tb", "v"];
function qR(r) {
  return JR.includes(r) || Do(r);
}
const eI = {
  [X_]: QR,
  [$_]: YR,
  [K_]: zR
};
function z_(r, e = {}) {
  const t = {};
  if (r == null || typeof r != "object")
    return t;
  const i = e.version || r.v || 1, s = e.reportingMode || K_, n = i === 1 ? qR : eI[s];
  let a = Object.keys(r).filter(n);
  const o = e.filter;
  typeof o == "function" && (a = a.filter(o));
  const c = s === X_ || s === $_;
  c && !a.includes("ts") && a.push("ts"), i > 1 && !a.includes("v") && a.push("v");
  const l = Me({}, $R, e.formatters), d = {
    version: i,
    reportingMode: s,
    baseUrl: e.baseUrl
  };
  return a.sort().forEach((h) => {
    let u = r[h];
    const f = l[h];
    if (typeof f == "function" && (u = f(u, d)), h === "v") {
      if (i === 1)
        return;
      u = i;
    }
    h == "pr" && u === 1 || (c && h === "ts" && !q(u) && (u = Date.now()), WR(u) && (VR(h) && typeof u == "string" && (u = new U_(u)), t[h] = u));
  }), t;
}
function tI(r, e = {}) {
  const t = {};
  if (!r)
    return t;
  const i = z_(r, e), s = UR(i, e == null ? void 0 : e.customHeaderMap);
  return Object.entries(s).reduce((n, [a, o]) => {
    const c = Z_(o, {
      whitespace: !1
    });
    return c && (n[a] = c), n;
  }, t);
}
function iI(r, e, t) {
  return Me(r, tI(e, t));
}
const sI = "CMCD";
function rI(r, e = {}) {
  return r ? Z_(z_(r, e), {
    whitespace: !1
  }) : "";
}
function nI(r, e = {}) {
  if (!r)
    return "";
  const t = rI(r, e);
  return encodeURIComponent(t);
}
function aI(r, e = {}) {
  if (!r)
    return "";
  const t = nI(r, e);
  return `${sI}=${t}`;
}
const Wp = /CMCD=[^&#]+/;
function oI(r, e, t) {
  const i = aI(e, t);
  if (!i)
    return r;
  if (Wp.test(r))
    return r.replace(Wp, i);
  const s = r.includes("?") ? "&" : "?";
  return `${r}${s}${i}`;
}
class lI {
  constructor(e) {
    this.hls = void 0, this.config = void 0, this.media = void 0, this.sid = void 0, this.cid = void 0, this.useHeaders = !1, this.includeKeys = void 0, this.initialized = !1, this.starved = !1, this.buffering = !0, this.audioBuffer = void 0, this.videoBuffer = void 0, this.onWaiting = () => {
      this.initialized && (this.starved = !0), this.buffering = !0;
    }, this.onPlaying = () => {
      this.initialized || (this.initialized = !0), this.buffering = !1;
    }, this.applyPlaylistData = (s) => {
      try {
        this.apply(s, {
          ot: It.MANIFEST,
          su: !this.initialized
        });
      } catch (n) {
        this.hls.logger.warn("Could not generate manifest CMCD data.", n);
      }
    }, this.applyFragmentData = (s) => {
      try {
        const {
          frag: n,
          part: a
        } = s, o = this.hls.levels[n.level], c = this.getObjectType(n), l = {
          d: (a || n).duration * 1e3,
          ot: c
        };
        (c === It.VIDEO || c === It.AUDIO || c == It.MUXED) && (l.br = o.bitrate / 1e3, l.tb = this.getTopBandwidth(c) / 1e3, l.bl = this.getBufferLength(c));
        const d = a ? this.getNextPart(a) : this.getNextFrag(n);
        d != null && d.url && d.url !== n.url && (l.nor = d.url), this.apply(s, l);
      } catch (n) {
        this.hls.logger.warn("Could not generate segment CMCD data.", n);
      }
    }, this.hls = e;
    const t = this.config = e.config, {
      cmcd: i
    } = t;
    i != null && (t.pLoader = this.createPlaylistLoader(), t.fLoader = this.createFragmentLoader(), this.sid = i.sessionId || e.sessionId, this.cid = i.contentId, this.useHeaders = i.useHeaders === !0, this.includeKeys = i.includeKeys, this.registerListeners());
  }
  registerListeners() {
    const e = this.hls;
    e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHED, this.onMediaDetached, this), e.on(T.BUFFER_CREATED, this.onBufferCreated, this);
  }
  unregisterListeners() {
    const e = this.hls;
    e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHED, this.onMediaDetached, this), e.off(T.BUFFER_CREATED, this.onBufferCreated, this);
  }
  destroy() {
    this.unregisterListeners(), this.onMediaDetached(), this.hls = this.config = this.audioBuffer = this.videoBuffer = null, this.onWaiting = this.onPlaying = this.media = null;
  }
  onMediaAttached(e, t) {
    this.media = t.media, this.media.addEventListener("waiting", this.onWaiting), this.media.addEventListener("playing", this.onPlaying);
  }
  onMediaDetached() {
    this.media && (this.media.removeEventListener("waiting", this.onWaiting), this.media.removeEventListener("playing", this.onPlaying), this.media = null);
  }
  onBufferCreated(e, t) {
    var i, s;
    this.audioBuffer = (i = t.tracks.audio) == null ? void 0 : i.buffer, this.videoBuffer = (s = t.tracks.video) == null ? void 0 : s.buffer;
  }
  /**
   * Create baseline CMCD data
   */
  createData() {
    var e;
    return {
      v: 1,
      sf: mR.HLS,
      sid: this.sid,
      cid: this.cid,
      pr: (e = this.media) == null ? void 0 : e.playbackRate,
      mtp: this.hls.bandwidthEstimate / 1e3
    };
  }
  /**
   * Apply CMCD data to a request.
   */
  apply(e, t = {}) {
    Me(t, this.createData());
    const i = t.ot === It.INIT || t.ot === It.VIDEO || t.ot === It.MUXED;
    this.starved && i && (t.bs = !0, t.su = !0, this.starved = !1), t.su == null && (t.su = this.buffering);
    const {
      includeKeys: s
    } = this;
    s && (t = Object.keys(t).reduce((a, o) => (s.includes(o) && (a[o] = t[o]), a), {}));
    const n = {
      baseUrl: e.url
    };
    this.useHeaders ? (e.headers || (e.headers = {}), iI(e.headers, t, n)) : e.url = oI(e.url, t, n);
  }
  getNextFrag(e) {
    var t;
    const i = (t = this.hls.levels[e.level]) == null ? void 0 : t.details;
    if (i) {
      const s = e.sn - i.startSN;
      return i.fragments[s + 1];
    }
  }
  getNextPart(e) {
    var t;
    const {
      index: i,
      fragment: s
    } = e, n = (t = this.hls.levels[s.level]) == null || (t = t.details) == null ? void 0 : t.partList;
    if (n) {
      const {
        sn: a
      } = s;
      for (let o = n.length - 1; o >= 0; o--) {
        const c = n[o];
        if (c.index === i && c.fragment.sn === a)
          return n[o + 1];
      }
    }
  }
  /**
   * The CMCD object type.
   */
  getObjectType(e) {
    const {
      type: t
    } = e;
    if (t === "subtitle")
      return It.TIMED_TEXT;
    if (e.sn === "initSegment")
      return It.INIT;
    if (t === "audio")
      return It.AUDIO;
    if (t === "main")
      return this.hls.audioTracks.length ? It.VIDEO : It.MUXED;
  }
  /**
   * Get the highest bitrate.
   */
  getTopBandwidth(e) {
    let t = 0, i;
    const s = this.hls;
    if (e === It.AUDIO)
      i = s.audioTracks;
    else {
      const n = s.maxAutoLevel, a = n > -1 ? n + 1 : s.levels.length;
      i = s.levels.slice(0, a);
    }
    return i.forEach((n) => {
      n.bitrate > t && (t = n.bitrate);
    }), t > 0 ? t : NaN;
  }
  /**
   * Get the buffer length for a media type in milliseconds
   */
  getBufferLength(e) {
    const t = this.media, i = e === It.AUDIO ? this.audioBuffer : this.videoBuffer;
    return !i || !t ? NaN : ce.bufferInfo(i, t.currentTime, this.config.maxBufferHole).len * 1e3;
  }
  /**
   * Create a playlist loader
   */
  createPlaylistLoader() {
    const {
      pLoader: e
    } = this.config, t = this.applyPlaylistData, i = e || this.config.loader;
    return class {
      constructor(n) {
        this.loader = void 0, this.loader = new i(n);
      }
      get stats() {
        return this.loader.stats;
      }
      get context() {
        return this.loader.context;
      }
      destroy() {
        this.loader.destroy();
      }
      abort() {
        this.loader.abort();
      }
      load(n, a, o) {
        t(n), this.loader.load(n, a, o);
      }
    };
  }
  /**
   * Create a playlist loader
   */
  createFragmentLoader() {
    const {
      fLoader: e
    } = this.config, t = this.applyFragmentData, i = e || this.config.loader;
    return class {
      constructor(n) {
        this.loader = void 0, this.loader = new i(n);
      }
      get stats() {
        return this.loader.stats;
      }
      get context() {
        return this.loader.context;
      }
      destroy() {
        this.loader.destroy();
      }
      abort() {
        this.loader.abort();
      }
      load(n, a, o) {
        t(n), this.loader.load(n, a, o);
      }
    };
  }
}
const cI = 3e5;
class dI extends qt {
  constructor(e) {
    super("content-steering", e.logger), this.hls = void 0, this.loader = null, this.uri = null, this.pathwayId = ".", this._pathwayPriority = null, this.timeToLoad = 300, this.reloadTimer = -1, this.updated = 0, this.started = !1, this.enabled = !0, this.levels = null, this.audioTracks = null, this.subtitleTracks = null, this.penalizedPathways = {}, this.hls = e, this.registerListeners();
  }
  registerListeners() {
    const e = this.hls;
    e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const e = this.hls;
    e && (e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.ERROR, this.onError, this));
  }
  pathways() {
    return (this.levels || []).reduce((e, t) => (e.indexOf(t.pathwayId) === -1 && e.push(t.pathwayId), e), []);
  }
  get pathwayPriority() {
    return this._pathwayPriority;
  }
  set pathwayPriority(e) {
    this.updatePathwayPriority(e);
  }
  startLoad() {
    if (this.started = !0, this.clearTimeout(), this.enabled && this.uri) {
      if (this.updated) {
        const e = this.timeToLoad * 1e3 - (performance.now() - this.updated);
        if (e > 0) {
          this.scheduleRefresh(this.uri, e);
          return;
        }
      }
      this.loadSteeringManifest(this.uri);
    }
  }
  stopLoad() {
    this.started = !1, this.loader && (this.loader.destroy(), this.loader = null), this.clearTimeout();
  }
  clearTimeout() {
    this.reloadTimer !== -1 && (self.clearTimeout(this.reloadTimer), this.reloadTimer = -1);
  }
  destroy() {
    this.unregisterListeners(), this.stopLoad(), this.hls = null, this.levels = this.audioTracks = this.subtitleTracks = null;
  }
  removeLevel(e) {
    const t = this.levels;
    t && (this.levels = t.filter((i) => i !== e));
  }
  onManifestLoading() {
    this.stopLoad(), this.enabled = !0, this.timeToLoad = 300, this.updated = 0, this.uri = null, this.pathwayId = ".", this.levels = this.audioTracks = this.subtitleTracks = null;
  }
  onManifestLoaded(e, t) {
    const {
      contentSteering: i
    } = t;
    i !== null && (this.pathwayId = i.pathwayId, this.uri = i.uri, this.started && this.startLoad());
  }
  onManifestParsed(e, t) {
    this.audioTracks = t.audioTracks, this.subtitleTracks = t.subtitleTracks;
  }
  onError(e, t) {
    const {
      errorAction: i
    } = t;
    if ((i == null ? void 0 : i.action) === ft.SendAlternateToPenaltyBox && i.flags === Vt.MoveAllAlternatesMatchingHost) {
      const s = this.levels;
      let n = this._pathwayPriority, a = this.pathwayId;
      if (t.context) {
        const {
          groupId: o,
          pathwayId: c,
          type: l
        } = t.context;
        o && s ? a = this.getPathwayForGroupId(o, l, a) : c && (a = c);
      }
      a in this.penalizedPathways || (this.penalizedPathways[a] = performance.now()), !n && s && (n = this.pathways()), n && n.length > 1 && (this.updatePathwayPriority(n), i.resolved = this.pathwayId !== a), t.details === V.BUFFER_APPEND_ERROR && !t.fatal ? i.resolved = !0 : i.resolved || this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s && s.length} priorities: ${Ze(n)} penalized: ${Ze(this.penalizedPathways)}`);
    }
  }
  filterParsedLevels(e) {
    this.levels = e;
    let t = this.getLevelsForPathway(this.pathwayId);
    if (t.length === 0) {
      const i = e[0].pathwayId;
      this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`), t = this.getLevelsForPathway(i), this.pathwayId = i;
    }
    return t.length !== e.length && this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`), t;
  }
  getLevelsForPathway(e) {
    return this.levels === null ? [] : this.levels.filter((t) => e === t.pathwayId);
  }
  updatePathwayPriority(e) {
    this._pathwayPriority = e;
    let t;
    const i = this.penalizedPathways, s = performance.now();
    Object.keys(i).forEach((n) => {
      s - i[n] > cI && delete i[n];
    });
    for (let n = 0; n < e.length; n++) {
      const a = e[n];
      if (a in i)
        continue;
      if (a === this.pathwayId)
        return;
      const o = this.hls.nextLoadLevel, c = this.hls.levels[o];
      if (t = this.getLevelsForPathway(a), t.length > 0) {
        this.log(`Setting Pathway to "${a}"`), this.pathwayId = a, m_(t), this.hls.trigger(T.LEVELS_UPDATED, {
          levels: t
        });
        const l = this.hls.levels[o];
        c && l && this.levels && (l.attrs["STABLE-VARIANT-ID"] !== c.attrs["STABLE-VARIANT-ID"] && l.bitrate !== c.bitrate && this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`), this.hls.nextLoadLevel = o);
        break;
      }
    }
  }
  getPathwayForGroupId(e, t, i) {
    const s = this.getLevelsForPathway(i).concat(this.levels || []);
    for (let n = 0; n < s.length; n++)
      if (t === me.AUDIO_TRACK && s[n].hasAudioGroup(e) || t === me.SUBTITLE_TRACK && s[n].hasSubtitleGroup(e))
        return s[n].pathwayId;
    return i;
  }
  clonePathways(e) {
    const t = this.levels;
    if (!t)
      return;
    const i = {}, s = {};
    e.forEach((n) => {
      const {
        ID: a,
        "BASE-ID": o,
        "URI-REPLACEMENT": c
      } = n;
      if (t.some((d) => d.pathwayId === a))
        return;
      const l = this.getLevelsForPathway(o).map((d) => {
        const h = new $e(d.attrs);
        h["PATHWAY-ID"] = a;
        const u = h.AUDIO && `${h.AUDIO}_clone_${a}`, f = h.SUBTITLES && `${h.SUBTITLES}_clone_${a}`;
        u && (i[h.AUDIO] = u, h.AUDIO = u), f && (s[h.SUBTITLES] = f, h.SUBTITLES = f);
        const p = j_(d.uri, h["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", c), m = new En({
          attrs: h,
          audioCodec: d.audioCodec,
          bitrate: d.bitrate,
          height: d.height,
          name: d.name,
          url: p,
          videoCodec: d.videoCodec,
          width: d.width
        });
        if (d.audioGroups)
          for (let g = 1; g < d.audioGroups.length; g++)
            m.addGroupId("audio", `${d.audioGroups[g]}_clone_${a}`);
        if (d.subtitleGroups)
          for (let g = 1; g < d.subtitleGroups.length; g++)
            m.addGroupId("text", `${d.subtitleGroups[g]}_clone_${a}`);
        return m;
      });
      t.push(...l), Hp(this.audioTracks, i, c, a), Hp(this.subtitleTracks, s, c, a);
    });
  }
  loadSteeringManifest(e) {
    const t = this.hls.config, i = t.loader;
    this.loader && this.loader.destroy(), this.loader = new i(t);
    let s;
    try {
      s = new self.URL(e);
    } catch {
      this.enabled = !1, this.log(`Failed to parse Steering Manifest URI: ${e}`);
      return;
    }
    if (s.protocol !== "data:") {
      const d = (this.hls.bandwidthEstimate || t.abrEwmaDefaultEstimate) | 0;
      s.searchParams.set("_HLS_pathway", this.pathwayId), s.searchParams.set("_HLS_throughput", "" + d);
    }
    const n = {
      responseType: "json",
      url: s.href
    }, a = t.steeringManifestLoadPolicy.default, o = a.errorRetry || a.timeoutRetry || {}, c = {
      loadPolicy: a,
      timeout: a.maxLoadTimeMs,
      maxRetry: o.maxNumRetry || 0,
      retryDelay: o.retryDelayMs || 0,
      maxRetryDelay: o.maxRetryDelayMs || 0
    }, l = {
      onSuccess: (d, h, u, f) => {
        this.log(`Loaded steering manifest: "${s}"`);
        const p = d.data;
        if ((p == null ? void 0 : p.VERSION) !== 1) {
          this.log(`Steering VERSION ${p.VERSION} not supported!`);
          return;
        }
        this.updated = performance.now(), this.timeToLoad = p.TTL;
        const {
          "RELOAD-URI": m,
          "PATHWAY-CLONES": g,
          "PATHWAY-PRIORITY": x
        } = p;
        if (m)
          try {
            this.uri = new self.URL(m, s).href;
          } catch {
            this.enabled = !1, this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);
            return;
          }
        this.scheduleRefresh(this.uri || u.url), g && this.clonePathways(g);
        const _ = {
          steeringManifest: p,
          url: s.toString()
        };
        this.hls.trigger(T.STEERING_MANIFEST_LOADED, _), x && this.updatePathwayPriority(x);
      },
      onError: (d, h, u, f) => {
        if (this.log(`Error loading steering manifest: ${d.code} ${d.text} (${h.url})`), this.stopLoad(), d.code === 410) {
          this.enabled = !1, this.log(`Steering manifest ${h.url} no longer available`);
          return;
        }
        let p = this.timeToLoad * 1e3;
        if (d.code === 429) {
          const m = this.loader;
          if (typeof (m == null ? void 0 : m.getResponseHeader) == "function") {
            const g = m.getResponseHeader("Retry-After");
            g && (p = parseFloat(g) * 1e3);
          }
          this.log(`Steering manifest ${h.url} rate limited`);
          return;
        }
        this.scheduleRefresh(this.uri || h.url, p);
      },
      onTimeout: (d, h, u) => {
        this.log(`Timeout loading steering manifest (${h.url})`), this.scheduleRefresh(this.uri || h.url);
      }
    };
    this.log(`Requesting steering manifest: ${s}`), this.loader.load(n, c, l);
  }
  scheduleRefresh(e, t = this.timeToLoad * 1e3) {
    this.clearTimeout(), this.reloadTimer = self.setTimeout(() => {
      var i;
      const s = (i = this.hls) == null ? void 0 : i.media;
      if (s && !s.ended) {
        this.loadSteeringManifest(e);
        return;
      }
      this.scheduleRefresh(e, this.timeToLoad * 1e3);
    }, t);
  }
}
function Hp(r, e, t, i) {
  r && Object.keys(e).forEach((s) => {
    const n = r.filter((a) => a.groupId === s).map((a) => {
      const o = Me({}, a);
      return o.details = void 0, o.attrs = new $e(o.attrs), o.url = o.attrs.URI = j_(a.url, a.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", t), o.groupId = o.attrs["GROUP-ID"] = e[s], o.attrs["PATHWAY-ID"] = i, o;
    });
    r.push(...n);
  });
}
function j_(r, e, t, i) {
  const {
    HOST: s,
    PARAMS: n,
    [t]: a
  } = i;
  let o;
  e && (o = a == null ? void 0 : a[e], o && (r = o));
  const c = new self.URL(r);
  return s && !o && (c.host = s), n && Object.keys(n).sort().forEach((l) => {
    l && c.searchParams.set(l, n[l]);
  }), c.href;
}
class Ar extends qt {
  constructor(e) {
    super("eme", e.logger), this.hls = void 0, this.config = void 0, this.media = null, this.keyFormatPromise = null, this.keySystemAccessPromises = {}, this._requestLicenseFailureCount = 0, this.mediaKeySessions = [], this.keyIdToKeySessionPromise = {}, this.mediaKeys = null, this.setMediaKeysQueue = Ar.CDMCleanupPromise ? [Ar.CDMCleanupPromise] : [], this.bannedKeyIds = {}, this.onMediaEncrypted = (t) => {
      const {
        initDataType: i,
        initData: s
      } = t, n = `"${t.type}" event: init data type: "${i}"`;
      if (this.debug(n), s !== null) {
        if (!this.keyFormatPromise) {
          let a = Object.keys(this.keySystemAccessPromises);
          a.length || (a = qr(this.config));
          const o = a.map(v0).filter((c) => !!c);
          this.keyFormatPromise = this.getKeyFormatPromise(o);
        }
        this.keyFormatPromise.then((a) => {
          const o = Pa(a);
          if (i !== "sinf" || o !== Qe.FAIRPLAY) {
            this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);
            return;
          }
          let c;
          try {
            const f = st(new Uint8Array(s)), p = Xd(JSON.parse(f).sinf), m = Yg(p);
            if (!m)
              throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");
            c = new Uint8Array(m.subarray(8, 24));
          } catch (f) {
            this.warn(`${n} Failed to parse sinf: ${f}`);
            return;
          }
          const l = Wt(c), {
            keyIdToKeySessionPromise: d,
            mediaKeySessions: h
          } = this;
          let u = d[l];
          for (let f = 0; f < h.length; f++) {
            const p = h[f], m = p.decryptdata;
            if (!m.keyId)
              continue;
            const g = Wt(m.keyId);
            if (l === g || m.uri.replace(/-/g, "").indexOf(l) !== -1) {
              if (u = d[g], !u)
                continue;
              if (m.pssh)
                break;
              delete d[g], m.pssh = new Uint8Array(s), m.keyId = c, u = d[l] = u.then(() => this.generateRequestWithPreferredKeySession(p, i, s, "encrypted-event-key-match")), u.catch((x) => this.handleError(x));
              break;
            }
          }
          u || this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`));
        }).catch((a) => this.handleError(a));
      }
    }, this.onWaitingForKey = (t) => {
      this.log(`"${t.type}" event`);
    }, this.hls = e, this.config = e.config, this.registerListeners();
  }
  destroy() {
    this.onDestroying(), this.onMediaDetached();
    const e = this.config;
    e.requestMediaKeySystemAccessFunc = null, e.licenseXhrSetup = e.licenseResponseCallback = void 0, e.drmSystems = e.drmSystemOptions = {}, this.hls = this.config = this.keyIdToKeySessionPromise = null, this.onMediaEncrypted = this.onWaitingForKey = null;
  }
  registerListeners() {
    this.hls.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), this.hls.on(T.MEDIA_DETACHED, this.onMediaDetached, this), this.hls.on(T.MANIFEST_LOADING, this.onManifestLoading, this), this.hls.on(T.MANIFEST_LOADED, this.onManifestLoaded, this), this.hls.on(T.DESTROYING, this.onDestroying, this);
  }
  unregisterListeners() {
    this.hls.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), this.hls.off(T.MEDIA_DETACHED, this.onMediaDetached, this), this.hls.off(T.MANIFEST_LOADING, this.onManifestLoading, this), this.hls.off(T.MANIFEST_LOADED, this.onManifestLoaded, this), this.hls.off(T.DESTROYING, this.onDestroying, this);
  }
  getLicenseServerUrl(e) {
    const {
      drmSystems: t,
      widevineLicenseUrl: i
    } = this.config, s = t == null ? void 0 : t[e];
    if (s)
      return s.licenseUrl;
    if (e === Qe.WIDEVINE && i)
      return i;
  }
  getLicenseServerUrlOrThrow(e) {
    const t = this.getLicenseServerUrl(e);
    if (t === void 0)
      throw new Error(`no license server URL configured for key-system "${e}"`);
    return t;
  }
  getServerCertificateUrl(e) {
    const {
      drmSystems: t
    } = this.config, i = t == null ? void 0 : t[e];
    if (i)
      return i.serverCertificateUrl;
    this.log(`No Server Certificate in config.drmSystems["${e}"]`);
  }
  attemptKeySystemAccess(e) {
    const t = this.hls.levels, i = (a, o, c) => !!a && c.indexOf(a) === o, s = t.map((a) => a.audioCodec).filter(i), n = t.map((a) => a.videoCodec).filter(i);
    return s.length + n.length === 0 && n.push("avc1.42e01e"), new Promise((a, o) => {
      const c = (l) => {
        const d = l.shift();
        this.getMediaKeysPromise(d, s, n).then((h) => a({
          keySystem: d,
          mediaKeys: h
        })).catch((h) => {
          l.length ? c(l) : h instanceof si ? o(h) : o(new si({
            type: ie.KEY_SYSTEM_ERROR,
            details: V.KEY_SYSTEM_NO_ACCESS,
            error: h,
            fatal: !0
          }, h.message));
        });
      };
      c(e);
    });
  }
  requestMediaKeySystemAccess(e, t) {
    const {
      requestMediaKeySystemAccessFunc: i
    } = this.config;
    if (typeof i != "function") {
      let s = `Configured requestMediaKeySystemAccess is not a function ${i}`;
      return l_ === null && self.location.protocol === "http:" && (s = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`), Promise.reject(new Error(s));
    }
    return i(e, t);
  }
  getMediaKeysPromise(e, t, i) {
    var s;
    const n = ZC(e, t, i, this.config.drmSystemOptions || {});
    let a = this.keySystemAccessPromises[e], o = (s = a) == null ? void 0 : s.keySystemAccess;
    if (!o) {
      this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ze(n)}`), o = this.requestMediaKeySystemAccess(e, n);
      const c = a = this.keySystemAccessPromises[e] = {
        keySystemAccess: o
      };
      return o.catch((l) => {
        this.log(`Failed to obtain access to key-system "${e}": ${l}`);
      }), o.then((l) => {
        this.log(`Access for key-system "${l.keySystem}" obtained`);
        const d = this.fetchServerCertificate(e);
        this.log(`Create media-keys for "${e}"`);
        const h = c.mediaKeys = l.createMediaKeys().then((u) => (this.log(`Media-keys created for "${e}"`), c.hasMediaKeys = !0, d.then((f) => f ? this.setMediaKeysServerCertificate(u, e, f) : u)));
        return h.catch((u) => {
          this.error(`Failed to create media-keys for "${e}"}: ${u}`);
        }), h;
      });
    }
    return o.then(() => a.mediaKeys);
  }
  createMediaKeySessionContext({
    decryptdata: e,
    keySystem: t,
    mediaKeys: i
  }) {
    this.log(`Creating key-system session "${t}" keyId: ${Wt(e.keyId || [])}`);
    const s = i.createSession(), n = {
      decryptdata: e,
      keySystem: t,
      mediaKeys: i,
      mediaKeysSession: s,
      keyStatus: "status-pending"
    };
    return this.mediaKeySessions.push(n), n;
  }
  renewKeySession(e) {
    const t = e.decryptdata;
    if (t.pssh) {
      const i = this.createMediaKeySessionContext(e), s = this.getKeyIdString(t), n = "cenc";
      this.keyIdToKeySessionPromise[s] = this.generateRequestWithPreferredKeySession(i, n, t.pssh.buffer, "expired");
    } else
      this.warn("Could not renew expired session. Missing pssh initData.");
    this.removeSession(e);
  }
  getKeyIdString(e) {
    if (!e)
      throw new Error("Could not read keyId of undefined decryptdata");
    if (e.keyId === null)
      throw new Error("keyId is null");
    return Wt(e.keyId);
  }
  updateKeySession(e, t) {
    const i = e.mediaKeysSession;
    return this.log(`Updating key-session "${i.sessionId}" for keyId ${Wt(e.decryptdata.keyId || [])}
      } (data length: ${t.byteLength})`), i.update(t);
  }
  getSelectedKeySystemFormats() {
    return Object.keys(this.keySystemAccessPromises).map((e) => ({
      keySystem: e,
      hasMediaKeys: this.keySystemAccessPromises[e].hasMediaKeys
    })).filter(({
      hasMediaKeys: e
    }) => !!e).map(({
      keySystem: e
    }) => v0(e)).filter((e) => !!e);
  }
  getKeySystemAccess(e) {
    return this.getKeySystemSelectionPromise(e).then(({
      keySystem: t,
      mediaKeys: i
    }) => this.attemptSetMediaKeys(t, i));
  }
  selectKeySystem(e) {
    return new Promise((t, i) => {
      this.getKeySystemSelectionPromise(e).then(({
        keySystem: s
      }) => {
        const n = v0(s);
        n ? t(n) : i(new Error(`Unable to find format for key-system "${s}"`));
      }).catch(i);
    });
  }
  selectKeySystemFormat(e) {
    const t = Object.keys(e.levelkeys || {});
    return this.keyFormatPromise || (this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`), this.keyFormatPromise = this.getKeyFormatPromise(t)), this.keyFormatPromise;
  }
  getKeyFormatPromise(e) {
    const t = qr(this.config), i = e.map(Pa).filter((s) => !!s && t.indexOf(s) !== -1);
    return this.selectKeySystem(i);
  }
  loadKey(e) {
    const t = e.keyInfo.decryptdata, i = this.getKeyIdString(t), s = this.bannedKeyIds[i];
    if (s) {
      const o = Zp(s, t);
      return this.handleError(o, e.frag), Promise.reject(o);
    }
    const n = `(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;
    this.log(`Starting session for key ${n}`);
    const a = this.keyIdToKeySessionPromise[i];
    if (!a) {
      const o = this.getKeySystemForKeyPromise(t).then(({
        keySystem: c,
        mediaKeys: l
      }) => (this.throwIfDestroyed(), this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`), this.attemptSetMediaKeys(c, l).then(() => (this.throwIfDestroyed(), this.createMediaKeySessionContext({
        keySystem: c,
        mediaKeys: l,
        decryptdata: t
      }))))).then((c) => {
        const l = "cenc", d = t.pssh ? t.pssh.buffer : null;
        return this.generateRequestWithPreferredKeySession(c, l, d, "playlist-key");
      });
      return o.catch((c) => this.handleError(c, e.frag)), this.keyIdToKeySessionPromise[i] = o, o;
    }
    return a;
  }
  throwIfDestroyed(e = "Invalid state") {
    if (!this.hls)
      throw new Error("invalid state");
  }
  handleError(e, t) {
    this.hls && (this.error(e.message), e instanceof si ? (t && (e.data.frag = t), this.hls.trigger(T.ERROR, e.data)) : this.hls.trigger(T.ERROR, {
      type: ie.KEY_SYSTEM_ERROR,
      details: V.KEY_SYSTEM_NO_KEYS,
      error: e,
      fatal: !0
    }));
  }
  getKeySystemForKeyPromise(e) {
    const t = this.getKeyIdString(e), i = this.keyIdToKeySessionPromise[t];
    if (!i) {
      const s = Pa(e.keyFormat), n = s ? [s] : qr(this.config);
      return this.attemptKeySystemAccess(n);
    }
    return i;
  }
  getKeySystemSelectionPromise(e) {
    if (e.length || (e = qr(this.config)), e.length === 0)
      throw new si({
        type: ie.KEY_SYSTEM_ERROR,
        details: V.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
        fatal: !0
      }, `Missing key-system license configuration options ${Ze({
        drmSystems: this.config.drmSystems
      })}`);
    return this.attemptKeySystemAccess(e);
  }
  attemptSetMediaKeys(e, t) {
    if (this.mediaKeys === t)
      return Promise.resolve();
    const i = this.setMediaKeysQueue.slice();
    this.log(`Setting media-keys for "${e}"`);
    const s = Promise.all(i).then(() => {
      if (!this.media)
        throw this.mediaKeys = null, new Error("Attempted to set mediaKeys without media element attached");
      return this.media.setMediaKeys(t);
    });
    return this.mediaKeys = t, this.setMediaKeysQueue.push(s), s.then(() => {
      this.log(`Media-keys set for "${e}"`), i.push(s), this.setMediaKeysQueue = this.setMediaKeysQueue.filter((n) => i.indexOf(n) === -1);
    });
  }
  generateRequestWithPreferredKeySession(e, t, i, s) {
    var n;
    const a = (n = this.config.drmSystems) == null || (n = n[e.keySystem]) == null ? void 0 : n.generateRequest;
    if (a)
      try {
        const u = a.call(this.hls, t, i, e);
        if (!u)
          throw new Error("Invalid response from configured generateRequest filter");
        t = u.initDataType, i = u.initData ? u.initData : null, e.decryptdata.pssh = i ? new Uint8Array(i) : null;
      } catch (u) {
        if (this.warn(u.message), this.hls && this.hls.config.debug)
          throw u;
      }
    if (i === null)
      return this.log(`Skipping key-session request for "${s}" (no initData)`), Promise.resolve(e);
    const o = this.getKeyIdString(e.decryptdata);
    this.log(`Generating key-session request for "${s}": ${o} (init data type: ${t} length: ${i.byteLength})`);
    const c = new zd(), l = e._onmessage = (u) => {
      const f = e.mediaKeysSession;
      if (!f) {
        c.emit("error", new Error("invalid state"));
        return;
      }
      const {
        messageType: p,
        message: m
      } = u;
      this.log(`"${p}" message event for session "${f.sessionId}" message size: ${m.byteLength}`), p === "license-request" || p === "license-renewal" ? this.renewLicense(e, m).catch((g) => {
        c.eventNames().length ? c.emit("error", g) : this.handleError(g);
      }) : p === "license-release" ? e.keySystem === Qe.FAIRPLAY && (this.updateKeySession(e, Mc("acknowledged")), this.removeSession(e)) : this.warn(`unhandled media key message type "${p}"`);
    }, d = e._onkeystatuseschange = (u) => {
      if (!e.mediaKeysSession) {
        c.emit("error", new Error("invalid state"));
        return;
      }
      const p = e.keyStatus;
      this.onKeyStatusChange(e);
      const m = e.keyStatus;
      m !== p && (c.emit("keyStatus", m, e), m === "expired" && (this.log(`${e.keySystem} expired for key ${o}`), this.renewKeySession(e)));
    };
    bt(e.mediaKeysSession, "message", l), bt(e.mediaKeysSession, "keystatuseschange", d);
    const h = new Promise((u, f) => {
      c.on("error", f), c.on("keyStatus", (p, {
        decryptdata: m
      }) => {
        p.startsWith("usable") ? u() : p === "internal-error" || p === "output-restricted" ? f(Zp(p, m)) : p === "expired" ? f(new Error(`key expired while generating request (keyId: ${o})`)) : this.warn(`unhandled key status change "${p}" (keyId: ${o})`);
      });
    });
    return e.mediaKeysSession.generateRequest(t, i).then(() => {
      this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o}`);
    }).catch((u) => {
      throw new si({
        type: ie.KEY_SYSTEM_ERROR,
        details: V.KEY_SYSTEM_NO_SESSION,
        error: u,
        decryptdata: e.decryptdata,
        fatal: !1
      }, `Error generating key-session request: ${u}`);
    }).then(() => h).catch((u) => {
      throw c.removeAllListeners(), this.removeSession(e), u;
    }).then(() => (c.removeAllListeners(), e));
  }
  onKeyStatusChange(e) {
    const t = Wt(new Uint8Array(e.decryptdata.keyId || []));
    e.mediaKeysSession.keyStatuses.forEach((i, s) => {
      if (typeof s == "string" && typeof i == "object") {
        const o = s;
        s = i, i = o;
      }
      const n = Wt("buffer" in s ? new Uint8Array(s.buffer, s.byteOffset, s.byteLength) : new Uint8Array(s));
      i === "internal-error" && (this.bannedKeyIds[n] = i);
      const a = n === t;
      this.log(`${a ? "" : "un"}matched key status change "${i}" for keyStatuses keyId: ${n} session keyId: ${t} uri: ${e.decryptdata.uri}`), a && (e.keyStatus = i);
    });
  }
  fetchServerCertificate(e) {
    const t = this.config, i = t.loader, s = new i(t), n = this.getServerCertificateUrl(e);
    return n ? (this.log(`Fetching server certificate for "${e}"`), new Promise((a, o) => {
      const c = {
        responseType: "arraybuffer",
        url: n
      }, l = t.certLoadPolicy.default, d = {
        loadPolicy: l,
        timeout: l.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0
      }, h = {
        onSuccess: (u, f, p, m) => {
          a(u.data);
        },
        onError: (u, f, p, m) => {
          o(new si({
            type: ie.KEY_SYSTEM_ERROR,
            details: V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
            fatal: !0,
            networkDetails: p,
            response: we({
              url: c.url,
              data: void 0
            }, u)
          }, `"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`));
        },
        onTimeout: (u, f, p) => {
          o(new si({
            type: ie.KEY_SYSTEM_ERROR,
            details: V.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
            fatal: !0,
            networkDetails: p,
            response: {
              url: c.url,
              data: void 0
            }
          }, `"${e}" certificate request timed out (${n})`));
        },
        onAbort: (u, f, p) => {
          o(new Error("aborted"));
        }
      };
      s.load(c, d, h);
    })) : Promise.resolve();
  }
  setMediaKeysServerCertificate(e, t, i) {
    return new Promise((s, n) => {
      e.setServerCertificate(i).then((a) => {
        this.log(`setServerCertificate ${a ? "success" : "not supported by CDM"} (${i.byteLength}) on "${t}"`), s(e);
      }).catch((a) => {
        n(new si({
          type: ie.KEY_SYSTEM_ERROR,
          details: V.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
          error: a,
          fatal: !0
        }, a.message));
      });
    });
  }
  renewLicense(e, t) {
    return this.requestLicense(e, new Uint8Array(t)).then((i) => this.updateKeySession(e, new Uint8Array(i)).catch((s) => {
      throw new si({
        type: ie.KEY_SYSTEM_ERROR,
        details: V.KEY_SYSTEM_SESSION_UPDATE_FAILED,
        decryptdata: e.decryptdata,
        error: s,
        fatal: !1
      }, s.message);
    }));
  }
  unpackPlayReadyKeyMessage(e, t) {
    const i = String.fromCharCode.apply(null, new Uint16Array(t.buffer));
    if (!i.includes("PlayReadyKeyMessage"))
      return e.setRequestHeader("Content-Type", "text/xml; charset=utf-8"), t;
    const s = new DOMParser().parseFromString(i, "application/xml"), n = s.querySelectorAll("HttpHeader");
    if (n.length > 0) {
      let d;
      for (let h = 0, u = n.length; h < u; h++) {
        var a, o;
        d = n[h];
        const f = (a = d.querySelector("name")) == null ? void 0 : a.textContent, p = (o = d.querySelector("value")) == null ? void 0 : o.textContent;
        f && p && e.setRequestHeader(f, p);
      }
    }
    const c = s.querySelector("Challenge"), l = c == null ? void 0 : c.textContent;
    if (!l)
      throw new Error("Cannot find <Challenge> in key message");
    return Mc(atob(l));
  }
  setupLicenseXHR(e, t, i, s) {
    const n = this.config.licenseXhrSetup;
    return n ? Promise.resolve().then(() => {
      if (!i.decryptdata)
        throw new Error("Key removed");
      return n.call(this.hls, e, t, i, s);
    }).catch((a) => {
      if (!i.decryptdata)
        throw a;
      return e.open("POST", t, !0), n.call(this.hls, e, t, i, s);
    }).then((a) => (e.readyState || e.open("POST", t, !0), {
      xhr: e,
      licenseChallenge: a || s
    })) : (e.open("POST", t, !0), Promise.resolve({
      xhr: e,
      licenseChallenge: s
    }));
  }
  requestLicense(e, t) {
    const i = this.config.keyLoadPolicy.default;
    return new Promise((s, n) => {
      const a = this.getLicenseServerUrlOrThrow(e.keySystem);
      this.log(`Sending license request to URL: ${a}`);
      const o = new XMLHttpRequest();
      o.responseType = "arraybuffer", o.onreadystatechange = () => {
        if (!this.hls || !e.mediaKeysSession)
          return n(new Error("invalid state"));
        if (o.readyState === 4)
          if (o.status === 200) {
            this._requestLicenseFailureCount = 0;
            let c = o.response;
            this.log(`License received ${c instanceof ArrayBuffer ? c.byteLength : c}`);
            const l = this.config.licenseResponseCallback;
            if (l)
              try {
                c = l.call(this.hls, o, a, e);
              } catch (d) {
                this.error(d);
              }
            s(c);
          } else {
            const c = i.errorRetry, l = c ? c.maxNumRetry : 0;
            if (this._requestLicenseFailureCount++, this._requestLicenseFailureCount > l || o.status >= 400 && o.status < 500)
              n(new si({
                type: ie.KEY_SYSTEM_ERROR,
                details: V.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
                decryptdata: e.decryptdata,
                fatal: !0,
                networkDetails: o,
                response: {
                  url: a,
                  data: void 0,
                  code: o.status,
                  text: o.statusText
                }
              }, `License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));
            else {
              const d = l - this._requestLicenseFailureCount + 1;
              this.warn(`Retrying license request, ${d} attempts left`), this.requestLicense(e, t).then(s, n);
            }
          }
      }, e.licenseXhr && e.licenseXhr.readyState !== XMLHttpRequest.DONE && e.licenseXhr.abort(), e.licenseXhr = o, this.setupLicenseXHR(o, a, e, t).then(({
        xhr: c,
        licenseChallenge: l
      }) => {
        e.keySystem == Qe.PLAYREADY && (l = this.unpackPlayReadyKeyMessage(c, l)), c.send(l);
      }).catch(n);
    });
  }
  onDestroying() {
    this.unregisterListeners(), this._clear();
  }
  onMediaAttached(e, t) {
    if (!this.config.emeEnabled)
      return;
    const i = t.media;
    this.media = i, bt(i, "encrypted", this.onMediaEncrypted), bt(i, "waitingforkey", this.onWaitingForKey);
  }
  onMediaDetached() {
    const e = this.media;
    e && (Ft(e, "encrypted", this.onMediaEncrypted), Ft(e, "waitingforkey", this.onWaitingForKey), this.media = null, this.mediaKeys = null);
  }
  _clear() {
    var e;
    if (this._requestLicenseFailureCount = 0, this.keyIdToKeySessionPromise = {}, this.bannedKeyIds = {}, !this.mediaKeys && !this.mediaKeySessions.length)
      return;
    const t = this.media, i = this.mediaKeySessions.slice();
    this.mediaKeySessions = [], this.mediaKeys = null, Io.clearKeyUriToKeyIdMap();
    const s = i.length;
    Ar.CDMCleanupPromise = Promise.all(i.map((n) => this.removeSession(n)).concat(t == null || (e = t.setMediaKeys(null)) == null ? void 0 : e.catch((n) => {
      this.log(`Could not clear media keys: ${n}`), this.hls && this.hls.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
        fatal: !1,
        error: new Error(`Could not clear media keys: ${n}`)
      });
    }))).catch((n) => {
      this.log(`Could not close sessions and clear media keys: ${n}`), this.hls && this.hls.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
        fatal: !1,
        error: new Error(`Could not close sessions and clear media keys: ${n}`)
      });
    }).then(() => {
      s && this.log("finished closing key sessions and clearing media keys");
    });
  }
  onManifestLoading() {
    this.keyFormatPromise = null, this.bannedKeyIds = {};
  }
  onManifestLoaded(e, {
    sessionKeys: t
  }) {
    if (!(!t || !this.config.emeEnabled) && !this.keyFormatPromise) {
      const i = t.reduce((s, n) => (s.indexOf(n.keyFormat) === -1 && s.push(n.keyFormat), s), []);
      this.log(`Selecting key-system from session-keys ${i.join(", ")}`), this.keyFormatPromise = this.getKeyFormatPromise(i);
    }
  }
  removeSession(e) {
    const {
      mediaKeysSession: t,
      licenseXhr: i,
      decryptdata: s
    } = e;
    if (t) {
      this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Wt((s == null ? void 0 : s.keyId) || [])}`), e._onmessage && (t.removeEventListener("message", e._onmessage), e._onmessage = void 0), e._onkeystatuseschange && (t.removeEventListener("keystatuseschange", e._onkeystatuseschange), e._onkeystatuseschange = void 0), i && i.readyState !== XMLHttpRequest.DONE && i.abort(), e.mediaKeysSession = e.decryptdata = e.licenseXhr = void 0;
      const n = this.mediaKeySessions.indexOf(e);
      n > -1 && this.mediaKeySessions.splice(n, 1);
      const {
        drmSystemOptions: a
      } = this.config;
      return (KC(a) ? new Promise((c, l) => {
        self.setTimeout(() => l(new Error("MediaKeySession.remove() timeout")), 8e3), t.remove().then(c).catch(l);
      }) : Promise.resolve()).catch((c) => {
        this.log(`Could not remove session: ${c}`), this.hls && this.hls.trigger(T.ERROR, {
          type: ie.OTHER_ERROR,
          details: V.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
          fatal: !1,
          error: new Error(`Could not remove session: ${c}`)
        });
      }).then(() => t.close()).catch((c) => {
        this.log(`Could not close session: ${c}`), this.hls && this.hls.trigger(T.ERROR, {
          type: ie.OTHER_ERROR,
          details: V.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
          fatal: !1,
          error: new Error(`Could not close session: ${c}`)
        });
      });
    }
  }
}
Ar.CDMCleanupPromise = void 0;
class si extends Error {
  constructor(e, t) {
    super(t), this.data = void 0, e.error || (e.error = new Error(t)), this.data = e, e.err = e.error;
  }
}
function Zp(r, e) {
  const t = r === "output-restricted", i = t ? V.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED : V.KEY_SYSTEM_STATUS_INTERNAL_ERROR;
  return new si({
    type: ie.KEY_SYSTEM_ERROR,
    details: i,
    fatal: !1,
    decryptdata: e
  }, t ? "HDCP level output restricted" : `key status changed to "${r}"`);
}
class hI {
  constructor(e) {
    this.hls = void 0, this.isVideoPlaybackQualityAvailable = !1, this.timer = void 0, this.media = null, this.lastTime = void 0, this.lastDroppedFrames = 0, this.lastDecodedFrames = 0, this.streamController = void 0, this.hls = e, this.registerListeners();
  }
  setStreamController(e) {
    this.streamController = e;
  }
  registerListeners() {
    this.hls.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), this.hls.on(T.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListeners() {
    this.hls.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), this.hls.off(T.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  destroy() {
    this.timer && clearInterval(this.timer), this.unregisterListeners(), this.isVideoPlaybackQualityAvailable = !1, this.media = null;
  }
  onMediaAttaching(e, t) {
    const i = this.hls.config;
    if (i.capLevelOnFPSDrop) {
      const s = t.media instanceof self.HTMLVideoElement ? t.media : null;
      this.media = s, s && typeof s.getVideoPlaybackQuality == "function" && (this.isVideoPlaybackQualityAvailable = !0), self.clearInterval(this.timer), this.timer = self.setInterval(this.checkFPSInterval.bind(this), i.fpsDroppedMonitoringPeriod);
    }
  }
  onMediaDetaching() {
    this.media = null;
  }
  checkFPS(e, t, i) {
    const s = performance.now();
    if (t) {
      if (this.lastTime) {
        const n = s - this.lastTime, a = i - this.lastDroppedFrames, o = t - this.lastDecodedFrames, c = 1e3 * a / n, l = this.hls;
        if (l.trigger(T.FPS_DROP, {
          currentDropped: a,
          currentDecoded: o,
          totalDroppedFrames: i
        }), c > 0 && a > l.config.fpsDroppedMonitoringThreshold * o) {
          let d = l.currentLevel;
          l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: " + d), d > 0 && (l.autoLevelCapping === -1 || l.autoLevelCapping >= d) && (d = d - 1, l.trigger(T.FPS_DROP_LEVEL_CAPPING, {
            level: d,
            droppedLevel: l.currentLevel
          }), l.autoLevelCapping = d, this.streamController.nextLevelSwitch());
        }
      }
      this.lastTime = s, this.lastDroppedFrames = i, this.lastDecodedFrames = t;
    }
  }
  checkFPSInterval() {
    const e = this.media;
    if (e)
      if (this.isVideoPlaybackQualityAvailable) {
        const t = e.getVideoPlaybackQuality();
        this.checkFPS(e, t.totalVideoFrames, t.droppedVideoFrames);
      } else
        this.checkFPS(e, e.webkitDecodedFrameCount, e.webkitDroppedFrameCount);
  }
}
function Q_(r, e) {
  let t;
  try {
    t = new Event("addtrack");
  } catch {
    t = document.createEvent("Event"), t.initEvent("addtrack", !1, !1);
  }
  t.track = r, e.dispatchEvent(t);
}
function J_(r, e) {
  const t = r.mode;
  if (t === "disabled" && (r.mode = "hidden"), r.cues && !r.cues.getCueById(e.id))
    try {
      if (r.addCue(e), !r.cues.getCueById(e.id))
        throw new Error(`addCue is failed for: ${e}`);
    } catch (i) {
      Pe.debug(`[texttrack-utils]: ${i}`);
      try {
        const s = new self.TextTrackCue(e.startTime, e.endTime, e.text);
        s.id = e.id, r.addCue(s);
      } catch (s) {
        Pe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`);
      }
    }
  t === "disabled" && (r.mode = t);
}
function mr(r, e) {
  const t = r.mode;
  if (t === "disabled" && (r.mode = "hidden"), r.cues)
    for (let i = r.cues.length; i--; )
      e && r.cues[i].removeEventListener("enter", e), r.removeCue(r.cues[i]);
  t === "disabled" && (r.mode = t);
}
function Hc(r, e, t, i) {
  const s = r.mode;
  if (s === "disabled" && (r.mode = "hidden"), r.cues && r.cues.length > 0) {
    const n = fI(r.cues, e, t);
    for (let a = 0; a < n.length; a++)
      (!i || i(n[a])) && r.removeCue(n[a]);
  }
  s === "disabled" && (r.mode = s);
}
function uI(r, e) {
  if (e <= r[0].startTime)
    return 0;
  const t = r.length - 1;
  if (e > r[t].endTime)
    return -1;
  let i = 0, s = t, n;
  for (; i <= s; )
    if (n = Math.floor((s + i) / 2), e < r[n].startTime)
      s = n - 1;
    else if (e > r[n].startTime && i < t)
      i = n + 1;
    else
      return n;
  return r[i].startTime - e < e - r[s].startTime ? i : s;
}
function fI(r, e, t) {
  const i = [], s = uI(r, e);
  if (s > -1)
    for (let n = s, a = r.length; n < a; n++) {
      const o = r[n];
      if (o.startTime >= e && o.endTime <= t)
        i.push(o);
      else if (o.startTime > t)
        return i;
    }
  return i;
}
function Ba(r) {
  const e = [];
  for (let t = 0; t < r.length; t++) {
    const i = r[t];
    (i.kind === "subtitles" || i.kind === "captions") && i.label && e.push(r[t]);
  }
  return e;
}
class pI extends ih {
  constructor(e) {
    super(e, "subtitle-track-controller"), this.media = null, this.tracks = [], this.groupIds = null, this.tracksInGroup = [], this.trackId = -1, this.currentTrack = null, this.selectDefaultTrack = !0, this.queuedDefaultTrack = -1, this.useTextTrackPolling = !1, this.subtitlePollingInterval = -1, this._subtitleDisplay = !0, this.asyncPollTrackChange = () => this.pollTrackChange(0), this.onTextTracksChanged = () => {
      if (this.useTextTrackPolling || self.clearInterval(this.subtitlePollingInterval), !this.media || !this.hls.config.renderTextTracksNatively)
        return;
      let t = null;
      const i = Ba(this.media.textTracks);
      for (let n = 0; n < i.length; n++)
        if (i[n].mode === "hidden")
          t = i[n];
        else if (i[n].mode === "showing") {
          t = i[n];
          break;
        }
      const s = this.findTrackForTextTrack(t);
      this.subtitleTrack !== s && this.setSubtitleTrack(s);
    }, this.registerListeners();
  }
  destroy() {
    this.unregisterListeners(), this.tracks.length = 0, this.tracksInGroup.length = 0, this.currentTrack = null, this.onTextTracksChanged = this.asyncPollTrackChange = null, super.destroy();
  }
  get subtitleDisplay() {
    return this._subtitleDisplay;
  }
  set subtitleDisplay(e) {
    this._subtitleDisplay = e, this.trackId > -1 && this.toggleTrackModes();
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.LEVEL_LOADING, this.onLevelLoading, this), e.on(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.on(T.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this), e.on(T.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.LEVEL_LOADING, this.onLevelLoading, this), e.off(T.LEVEL_SWITCHING, this.onLevelSwitching, this), e.off(T.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this), e.off(T.ERROR, this.onError, this);
  }
  // Listen for subtitle track change, then extract the current track ID.
  onMediaAttached(e, t) {
    this.media = t.media, this.media && (this.queuedDefaultTrack > -1 && (this.subtitleTrack = this.queuedDefaultTrack, this.queuedDefaultTrack = -1), this.useTextTrackPolling = !(this.media.textTracks && "onchange" in this.media.textTracks), this.useTextTrackPolling ? this.pollTrackChange(500) : this.media.textTracks.addEventListener("change", this.asyncPollTrackChange));
  }
  pollTrackChange(e) {
    self.clearInterval(this.subtitlePollingInterval), this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, e);
  }
  onMediaDetaching(e, t) {
    const i = this.media;
    if (!i)
      return;
    const s = !!t.transferMedia;
    if (self.clearInterval(this.subtitlePollingInterval), this.useTextTrackPolling || i.textTracks.removeEventListener("change", this.asyncPollTrackChange), this.trackId > -1 && (this.queuedDefaultTrack = this.trackId), this.subtitleTrack = -1, this.media = null, s)
      return;
    Ba(i.textTracks).forEach((a) => {
      mr(a);
    });
  }
  onManifestLoading() {
    this.tracks = [], this.groupIds = null, this.tracksInGroup = [], this.trackId = -1, this.currentTrack = null, this.selectDefaultTrack = !0;
  }
  // Fired whenever a new manifest is loaded.
  onManifestParsed(e, t) {
    this.tracks = t.subtitleTracks;
  }
  onSubtitleTrackLoaded(e, t) {
    const {
      id: i,
      groupId: s,
      details: n
    } = t, a = this.tracksInGroup[i];
    if (!a || a.groupId !== s) {
      this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a == null ? void 0 : a.groupId}`);
      return;
    }
    const o = a.details;
    a.details = t.details, this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`), i === this.trackId && this.playlistLoaded(i, t, o);
  }
  onLevelLoading(e, t) {
    this.switchLevel(t.level);
  }
  onLevelSwitching(e, t) {
    this.switchLevel(t.level);
  }
  switchLevel(e) {
    const t = this.hls.levels[e];
    if (!t)
      return;
    const i = t.subtitleGroups || null, s = this.groupIds;
    let n = this.currentTrack;
    if (!i || (s == null ? void 0 : s.length) !== (i == null ? void 0 : i.length) || i != null && i.some((a) => (s == null ? void 0 : s.indexOf(a)) === -1)) {
      this.groupIds = i, this.trackId = -1, this.currentTrack = null;
      const a = this.tracks.filter((d) => !i || i.indexOf(d.groupId) !== -1);
      if (a.length)
        this.selectDefaultTrack && !a.some((d) => d.default) && (this.selectDefaultTrack = !1), a.forEach((d, h) => {
          d.id = h;
        });
      else if (!n && !this.tracksInGroup.length)
        return;
      this.tracksInGroup = a;
      const o = this.hls.config.subtitlePreference;
      if (!n && o) {
        this.selectDefaultTrack = !1;
        const d = Di(o, a);
        if (d > -1)
          n = a[d];
        else {
          const h = Di(o, this.tracks);
          n = this.tracks[h];
        }
      }
      let c = this.findTrackId(n);
      c === -1 && n && (c = this.findTrackId(null));
      const l = {
        subtitleTracks: a
      };
      this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i == null ? void 0 : i.join(",")}" group-id`), this.hls.trigger(T.SUBTITLE_TRACKS_UPDATED, l), c !== -1 && this.trackId === -1 && this.setSubtitleTrack(c);
    }
  }
  findTrackId(e) {
    const t = this.tracksInGroup, i = this.selectDefaultTrack;
    for (let s = 0; s < t.length; s++) {
      const n = t[s];
      if (!(i && !n.default || !i && !e) && (!e || Bs(n, e)))
        return s;
    }
    if (e) {
      for (let s = 0; s < t.length; s++) {
        const n = t[s];
        if (An(e.attrs, n.attrs, ["LANGUAGE", "ASSOC-LANGUAGE", "CHARACTERISTICS"]))
          return s;
      }
      for (let s = 0; s < t.length; s++) {
        const n = t[s];
        if (An(e.attrs, n.attrs, ["LANGUAGE"]))
          return s;
      }
    }
    return -1;
  }
  findTrackForTextTrack(e) {
    if (e) {
      const t = this.tracksInGroup;
      for (let i = 0; i < t.length; i++) {
        const s = t[i];
        if (Gc(s, e))
          return i;
      }
    }
    return -1;
  }
  onError(e, t) {
    t.fatal || !t.context || t.context.type === me.SUBTITLE_TRACK && t.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(t.context.groupId) !== -1) && this.checkRetry(t);
  }
  get allSubtitleTracks() {
    return this.tracks;
  }
  /** get alternate subtitle tracks list from playlist **/
  get subtitleTracks() {
    return this.tracksInGroup;
  }
  /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  get subtitleTrack() {
    return this.trackId;
  }
  set subtitleTrack(e) {
    this.selectDefaultTrack = !1, this.setSubtitleTrack(e);
  }
  setSubtitleOption(e) {
    if (this.hls.config.subtitlePreference = e, e) {
      if (e.id === -1)
        return this.setSubtitleTrack(-1), null;
      const t = this.allSubtitleTracks;
      if (this.selectDefaultTrack = !1, t.length) {
        const i = this.currentTrack;
        if (i && Bs(e, i))
          return i;
        const s = Di(e, this.tracksInGroup);
        if (s > -1) {
          const n = this.tracksInGroup[s];
          return this.setSubtitleTrack(s), n;
        } else {
          if (i)
            return null;
          {
            const n = Di(e, t);
            if (n > -1)
              return t[n];
          }
        }
      }
    }
    return null;
  }
  loadPlaylist(e) {
    super.loadPlaylist(), this.shouldLoadPlaylist(this.currentTrack) && this.scheduleLoading(this.currentTrack, e);
  }
  loadingPlaylist(e, t) {
    super.loadingPlaylist(e, t);
    const i = e.id, s = e.groupId, n = this.getUrlWithDirectives(e.url, t), a = e.details, o = a == null ? void 0 : a.age;
    this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${(t == null ? void 0 : t.msn) !== void 0 ? " at sn " + t.msn + " part " + t.part : ""}${o && a.live ? " age " + o.toFixed(1) + (a.type && " " + a.type || "") : ""} ${n}`), this.hls.trigger(T.SUBTITLE_TRACK_LOADING, {
      url: n,
      id: i,
      groupId: s,
      deliveryDirectives: t || null,
      track: e
    });
  }
  /**
   * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
   * This operates on the DOM textTracks.
   * A value of -1 will disable all subtitle tracks.
   */
  toggleTrackModes() {
    const {
      media: e
    } = this;
    if (!e)
      return;
    const t = Ba(e.textTracks), i = this.currentTrack;
    let s;
    if (i && (s = t.filter((n) => Gc(i, n))[0], s || this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)), [].slice.call(t).forEach((n) => {
      n.mode !== "disabled" && n !== s && (n.mode = "disabled");
    }), s) {
      const n = this.subtitleDisplay ? "showing" : "hidden";
      s.mode !== n && (s.mode = n);
    }
  }
  /**
   * This method is responsible for validating the subtitle index and periodically reloading if live.
   * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
   */
  setSubtitleTrack(e) {
    const t = this.tracksInGroup;
    if (!this.media) {
      this.queuedDefaultTrack = e;
      return;
    }
    if (e < -1 || e >= t.length || !q(e)) {
      this.warn(`Invalid subtitle track id: ${e}`);
      return;
    }
    this.selectDefaultTrack = !1;
    const i = this.currentTrack, s = t[e] || null;
    if (this.trackId = e, this.currentTrack = s, this.toggleTrackModes(), !s) {
      this.hls.trigger(T.SUBTITLE_TRACK_SWITCH, {
        id: e
      });
      return;
    }
    const n = !!s.details && !s.details.live;
    if (e === this.trackId && s === i && n)
      return;
    this.log(`Switching to subtitle-track ${e}` + (s ? ` "${s.name}" lang:${s.lang} group:${s.groupId}` : ""));
    const {
      id: a,
      groupId: o = "",
      name: c,
      type: l,
      url: d
    } = s;
    this.hls.trigger(T.SUBTITLE_TRACK_SWITCH, {
      id: a,
      groupId: o,
      name: c,
      type: l,
      url: d
    });
    const h = this.switchParams(s.url, i == null ? void 0 : i.details, s.details);
    this.loadPlaylist(h);
  }
}
function mI() {
  try {
    return crypto.randomUUID();
  } catch {
    try {
      const e = URL.createObjectURL(new Blob()), t = e.toString();
      return URL.revokeObjectURL(e), t.slice(t.lastIndexOf("/") + 1);
    } catch {
      let t = (/* @__PURE__ */ new Date()).getTime();
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s) => {
        const n = (t + Math.random() * 16) % 16 | 0;
        return t = Math.floor(t / 16), (s == "x" ? n : n & 3 | 8).toString(16);
      });
    }
  }
}
function dn(r) {
  let e = 5381, t = r.length;
  for (; t; )
    e = e * 33 ^ r.charCodeAt(--t);
  return (e >>> 0).toString();
}
const Cr = 0.025;
let co = /* @__PURE__ */ function(r) {
  return r[r.Point = 0] = "Point", r[r.Range = 1] = "Range", r;
}({});
function gI(r, e, t) {
  return `${r.identifier}-${t + 1}-${dn(e)}`;
}
class _I {
  constructor(e, t) {
    this.base = void 0, this._duration = null, this._timelineStart = null, this.appendInPlaceDisabled = void 0, this.appendInPlaceStarted = void 0, this.dateRange = void 0, this.hasPlayed = !1, this.cumulativeDuration = 0, this.resumeOffset = NaN, this.playoutLimit = NaN, this.restrictions = {
      skip: !1,
      jump: !1
    }, this.snapOptions = {
      out: !1,
      in: !1
    }, this.assetList = [], this.assetListLoader = void 0, this.assetListResponse = null, this.resumeAnchor = void 0, this.error = void 0, this.resetOnResume = void 0, this.base = t, this.dateRange = e, this.setDateRange(e);
  }
  setDateRange(e) {
    this.dateRange = e, this.resumeOffset = e.attr.optionalFloat("X-RESUME-OFFSET", this.resumeOffset), this.playoutLimit = e.attr.optionalFloat("X-PLAYOUT-LIMIT", this.playoutLimit), this.restrictions = e.attr.enumeratedStringList("X-RESTRICT", this.restrictions), this.snapOptions = e.attr.enumeratedStringList("X-SNAP", this.snapOptions);
  }
  reset() {
    var e;
    this.appendInPlaceStarted = !1, (e = this.assetListLoader) == null || e.destroy(), this.assetListLoader = void 0, this.supplementsPrimary || (this.assetListResponse = null, this.assetList = [], this._duration = null);
  }
  isAssetPastPlayoutLimit(e) {
    var t;
    if (e > 0 && e >= this.assetList.length)
      return !0;
    const i = this.playoutLimit;
    return e <= 0 || isNaN(i) ? !1 : i === 0 ? !0 : (((t = this.assetList[e]) == null ? void 0 : t.startOffset) || 0) > i;
  }
  findAssetIndex(e) {
    return this.assetList.indexOf(e);
  }
  get identifier() {
    return this.dateRange.id;
  }
  get startDate() {
    return this.dateRange.startDate;
  }
  get startTime() {
    const e = this.dateRange.startTime;
    if (this.snapOptions.out) {
      const t = this.dateRange.tagAnchor;
      if (t)
        return L0(e, t);
    }
    return e;
  }
  get startOffset() {
    return this.cue.pre ? 0 : this.startTime;
  }
  get startIsAligned() {
    if (this.startTime === 0 || this.snapOptions.out)
      return !0;
    const e = this.dateRange.tagAnchor;
    if (e) {
      const t = this.dateRange.startTime, i = L0(t, e);
      return t - i < 0.1;
    }
    return !1;
  }
  get resumptionOffset() {
    const e = this.resumeOffset, t = q(e) ? e : this.duration;
    return this.cumulativeDuration + t;
  }
  get resumeTime() {
    const e = this.startOffset + this.resumptionOffset;
    if (this.snapOptions.in) {
      const t = this.resumeAnchor;
      if (t)
        return L0(e, t);
    }
    return e;
  }
  get appendInPlace() {
    return this.appendInPlaceStarted ? !0 : this.appendInPlaceDisabled ? !1 : !!(!this.cue.once && !this.cue.pre && // preroll starts at startPosition before startPosition is known (live)
    this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < Cr));
  }
  set appendInPlace(e) {
    if (this.appendInPlaceStarted) {
      this.resetOnResume = !e;
      return;
    }
    this.appendInPlaceDisabled = !e;
  }
  // Extended timeline start time
  get timelineStart() {
    return this._timelineStart !== null ? this._timelineStart : this.startTime;
  }
  set timelineStart(e) {
    this._timelineStart = e;
  }
  get duration() {
    const e = this.playoutLimit;
    let t;
    return this._duration !== null ? t = this._duration : this.dateRange.duration ? t = this.dateRange.duration : t = this.dateRange.plannedDuration || 0, !isNaN(e) && e < t && (t = e), t;
  }
  set duration(e) {
    this._duration = e;
  }
  get cue() {
    return this.dateRange.cue;
  }
  get timelineOccupancy() {
    return this.dateRange.attr["X-TIMELINE-OCCUPIES"] === "RANGE" ? co.Range : co.Point;
  }
  get supplementsPrimary() {
    return this.dateRange.attr["X-TIMELINE-STYLE"] === "PRIMARY";
  }
  get contentMayVary() {
    return this.dateRange.attr["X-CONTENT-MAY-VARY"] !== "NO";
  }
  get assetUrl() {
    return this.dateRange.attr["X-ASSET-URI"];
  }
  get assetListUrl() {
    return this.dateRange.attr["X-ASSET-LIST"];
  }
  get baseUrl() {
    return this.base.url;
  }
  get assetListLoaded() {
    return this.assetList.length > 0 || this.assetListResponse !== null;
  }
  toString() {
    return yI(this);
  }
}
function L0(r, e) {
  return r - e.start < e.duration / 2 && !(Math.abs(r - (e.start + e.duration)) < Cr) ? e.start : e.start + e.duration;
}
function q_(r, e, t) {
  const i = new self.URL(r, t);
  return i.protocol !== "data:" && i.searchParams.set("_HLS_primary_id", e), i;
}
function D0(r, e) {
  for (; (t = r.assetList[++e]) != null && t.error; )
    var t;
  return e;
}
function yI(r) {
  return `["${r.identifier}" ${r.cue.pre ? "<pre>" : r.cue.post ? "<post>" : ""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`;
}
function dr(r) {
  const e = r.timelineStart, t = r.duration || 0;
  return `["${r.identifier}" ${e.toFixed(2)}-${(e + t).toFixed(2)}]`;
}
class xI {
  constructor(e, t, i, s) {
    this.hls = void 0, this.interstitial = void 0, this.assetItem = void 0, this.tracks = null, this.hasDetails = !1, this.mediaAttached = null, this._currentTime = void 0, this._bufferedEosTime = void 0, this.checkPlayout = () => {
      this.reachedPlayout(this.currentTime) && this.hls && this.hls.trigger(T.PLAYOUT_LIMIT_REACHED, {});
    };
    const n = this.hls = new e(t);
    this.interstitial = i, this.assetItem = s;
    const a = () => {
      this.hasDetails = !0;
    };
    n.once(T.LEVEL_LOADED, a), n.once(T.AUDIO_TRACK_LOADED, a), n.once(T.SUBTITLE_TRACK_LOADED, a), n.on(T.MEDIA_ATTACHING, (o, {
      media: c
    }) => {
      this.removeMediaListeners(), this.mediaAttached = c, this.interstitial.playoutLimit && (c.addEventListener("timeupdate", this.checkPlayout), this.appendInPlace && n.on(T.BUFFER_APPENDED, () => {
        const d = this.bufferedEnd;
        this.reachedPlayout(d) && (this._bufferedEosTime = d, n.trigger(T.BUFFERED_TO_END, void 0));
      }));
    });
  }
  get appendInPlace() {
    return this.interstitial.appendInPlace;
  }
  loadSource() {
    const e = this.hls;
    if (e)
      if (e.url)
        e.levels.length && !e.started && e.startLoad(-1, !0);
      else {
        let t = this.assetItem.uri;
        try {
          t = q_(t, e.config.primarySessionId || "").href;
        } catch {
        }
        e.loadSource(t);
      }
  }
  bufferedInPlaceToEnd(e) {
    var t;
    if (!this.appendInPlace)
      return !1;
    if ((t = this.hls) != null && t.bufferedToEnd)
      return !0;
    if (!e)
      return !1;
    const i = Math.min(this._bufferedEosTime || 1 / 0, this.duration), s = this.timelineOffset, n = ce.bufferInfo(e, s, 0);
    return this.getAssetTime(n.end) >= i - 0.02;
  }
  reachedPlayout(e) {
    const i = this.interstitial.playoutLimit;
    return this.startOffset + e >= i;
  }
  get destroyed() {
    var e;
    return !((e = this.hls) != null && e.userConfig);
  }
  get assetId() {
    return this.assetItem.identifier;
  }
  get interstitialId() {
    return this.assetItem.parentIdentifier;
  }
  get media() {
    var e;
    return ((e = this.hls) == null ? void 0 : e.media) || null;
  }
  get bufferedEnd() {
    const e = this.media || this.mediaAttached;
    if (!e)
      return this._bufferedEosTime ? this._bufferedEosTime : this.currentTime;
    const t = ce.bufferInfo(e, e.currentTime, 1e-3);
    return this.getAssetTime(t.end);
  }
  get currentTime() {
    const e = this.media || this.mediaAttached;
    return e ? this.getAssetTime(e.currentTime) : this._currentTime || 0;
  }
  get duration() {
    const e = this.assetItem.duration;
    if (!e)
      return 0;
    const t = this.interstitial.playoutLimit;
    if (t) {
      const i = t - this.startOffset;
      if (i > 0 && i < e)
        return i;
    }
    return e;
  }
  get remaining() {
    const e = this.duration;
    return e ? Math.max(0, e - this.currentTime) : 0;
  }
  get startOffset() {
    return this.assetItem.startOffset;
  }
  get timelineOffset() {
    var e;
    return ((e = this.hls) == null ? void 0 : e.config.timelineOffset) || 0;
  }
  set timelineOffset(e) {
    const t = this.timelineOffset;
    if (e !== t) {
      const i = e - t;
      if (Math.abs(i) > 1 / 9e4 && this.hls) {
        if (this.hasDetails)
          throw new Error("Cannot set timelineOffset after playlists are loaded");
        this.hls.config.timelineOffset = e;
      }
    }
  }
  getAssetTime(e) {
    const t = this.timelineOffset, i = this.duration;
    return Math.min(Math.max(0, e - t), i);
  }
  removeMediaListeners() {
    const e = this.mediaAttached;
    e && (this._currentTime = e.currentTime, this.bufferSnapShot(), e.removeEventListener("timeupdate", this.checkPlayout));
  }
  bufferSnapShot() {
    if (this.mediaAttached) {
      var e;
      (e = this.hls) != null && e.bufferedToEnd && (this._bufferedEosTime = this.bufferedEnd);
    }
  }
  destroy() {
    this.removeMediaListeners(), this.hls && this.hls.destroy(), this.hls = null, this.tracks = this.mediaAttached = this.checkPlayout = null;
  }
  attachMedia(e) {
    var t;
    this.loadSource(), (t = this.hls) == null || t.attachMedia(e);
  }
  detachMedia() {
    var e;
    this.removeMediaListeners(), this.mediaAttached = null, (e = this.hls) == null || e.detachMedia();
  }
  resumeBuffering() {
    var e;
    (e = this.hls) == null || e.resumeBuffering();
  }
  pauseBuffering() {
    var e;
    (e = this.hls) == null || e.pauseBuffering();
  }
  transferMedia() {
    var e;
    return this.bufferSnapShot(), ((e = this.hls) == null ? void 0 : e.transferMedia()) || null;
  }
  resetDetails() {
    const e = this.hls;
    if (e && this.hasDetails) {
      e.stopLoad();
      const t = (i) => delete i.details;
      e.levels.forEach(t), e.allAudioTracks.forEach(t), e.allSubtitleTracks.forEach(t), this.hasDetails = !1;
    }
  }
  on(e, t, i) {
    var s;
    (s = this.hls) == null || s.on(e, t);
  }
  once(e, t, i) {
    var s;
    (s = this.hls) == null || s.once(e, t);
  }
  off(e, t, i) {
    var s;
    (s = this.hls) == null || s.off(e, t);
  }
  toString() {
    var e;
    return `HlsAssetPlayer: ${dr(this.assetItem)} ${(e = this.hls) == null ? void 0 : e.sessionId} ${this.appendInPlace ? "append-in-place" : ""}`;
  }
}
const $p = 0.033;
class vI extends qt {
  constructor(e, t) {
    super("interstitials-sched", t), this.onScheduleUpdate = void 0, this.eventMap = {}, this.events = null, this.items = null, this.durations = {
      primary: 0,
      playout: 0,
      integrated: 0
    }, this.onScheduleUpdate = e;
  }
  destroy() {
    this.reset(), this.onScheduleUpdate = null;
  }
  reset() {
    this.eventMap = {}, this.setDurations(0, 0, 0), this.events && this.events.forEach((e) => e.reset()), this.events = this.items = null;
  }
  resetErrorsInRange(e, t) {
    return this.events ? this.events.reduce((i, s) => e <= s.startOffset && t > s.startOffset ? (delete s.error, i + 1) : i, 0) : 0;
  }
  get duration() {
    const e = this.items;
    return e ? e[e.length - 1].end : 0;
  }
  get length() {
    return this.items ? this.items.length : 0;
  }
  getEvent(e) {
    return e && this.eventMap[e] || null;
  }
  hasEvent(e) {
    return e in this.eventMap;
  }
  findItemIndex(e, t) {
    if (e.event)
      return this.findEventIndex(e.event.identifier);
    let i = -1;
    e.nextEvent ? i = this.findEventIndex(e.nextEvent.identifier) - 1 : e.previousEvent && (i = this.findEventIndex(e.previousEvent.identifier) + 1);
    const s = this.items;
    if (s)
      for (s[i] || (t === void 0 && (t = e.start), i = this.findItemIndexAtTime(t)); i >= 0 && (n = s[i]) != null && n.event; ) {
        var n;
        i--;
      }
    return i;
  }
  findItemIndexAtTime(e, t) {
    const i = this.items;
    if (i)
      for (let s = 0; s < i.length; s++) {
        let n = i[s];
        if (t && t !== "primary" && (n = n[t]), e === n.start || e > n.start && e < n.end)
          return s;
      }
    return -1;
  }
  findJumpRestrictedIndex(e, t) {
    const i = this.items;
    if (i)
      for (let s = e; s <= t && i[s]; s++) {
        const n = i[s].event;
        if (n != null && n.restrictions.jump && !n.appendInPlace)
          return s;
      }
    return -1;
  }
  findEventIndex(e) {
    const t = this.items;
    if (t)
      for (let s = t.length; s--; ) {
        var i;
        if (((i = t[s].event) == null ? void 0 : i.identifier) === e)
          return s;
      }
    return -1;
  }
  findAssetIndex(e, t) {
    const i = e.assetList, s = i.length;
    if (s > 1)
      for (let n = 0; n < s; n++) {
        const a = i[n];
        if (!a.error) {
          const o = a.timelineStart;
          if (t === o || t > o && (t < o + (a.duration || 0) || n === s - 1))
            return n;
        }
      }
    return 0;
  }
  get assetIdAtEnd() {
    var e;
    const t = (e = this.items) == null || (e = e[this.length - 1]) == null ? void 0 : e.event;
    if (t) {
      const i = t.assetList, s = i[i.length - 1];
      if (s)
        return s.identifier;
    }
    return null;
  }
  parseInterstitialDateRanges(e, t) {
    const i = e.main.details, {
      dateRanges: s
    } = i, n = this.events, a = this.parseDateRanges(s, {
      url: i.url
    }, t), o = Object.keys(s), c = n ? n.filter((l) => !o.includes(l.identifier)) : [];
    a.length && a.sort((l, d) => {
      const h = l.cue.pre, u = l.cue.post, f = d.cue.pre, p = d.cue.post;
      if (h && !f)
        return -1;
      if (f && !h || u && !p)
        return 1;
      if (p && !u)
        return -1;
      if (!h && !f && !u && !p) {
        const m = l.startTime, g = d.startTime;
        if (m !== g)
          return m - g;
      }
      return l.dateRange.tagOrder - d.dateRange.tagOrder;
    }), this.events = a, c.forEach((l) => {
      this.removeEvent(l);
    }), this.updateSchedule(e, c);
  }
  updateSchedule(e, t = [], i = !1) {
    const s = this.events || [];
    if (s.length || t.length || this.length < 2) {
      const n = this.items, a = this.parseSchedule(s, e);
      (i || t.length || (n == null ? void 0 : n.length) !== a.length || a.some((c, l) => Math.abs(c.playout.start - n[l].playout.start) > 5e-3 || Math.abs(c.playout.end - n[l].playout.end) > 5e-3)) && (this.items = a, this.onScheduleUpdate(t, n));
    }
  }
  parseDateRanges(e, t, i) {
    const s = [], n = Object.keys(e);
    for (let a = 0; a < n.length; a++) {
      const o = n[a], c = e[o];
      if (c.isInterstitial) {
        let l = this.eventMap[o];
        l ? l.setDateRange(c) : (l = new _I(c, t), this.eventMap[o] = l, i === !1 && (l.appendInPlace = i)), s.push(l);
      }
    }
    return s;
  }
  parseSchedule(e, t) {
    const i = [], s = t.main.details, n = s.live ? 1 / 0 : s.edge;
    let a = 0;
    if (e = e.filter((c) => !c.error && !(c.cue.once && c.hasPlayed)), e.length) {
      this.resolveOffsets(e, t);
      let c = 0, l = 0;
      if (e.forEach((d, h) => {
        const u = d.cue.pre, f = d.cue.post, p = e[h - 1] || null, m = d.appendInPlace, g = f ? n : d.startOffset, x = d.duration, _ = d.timelineOccupancy === co.Range ? x : 0, v = d.resumptionOffset, E = (p == null ? void 0 : p.startTime) === g, b = g + d.cumulativeDuration;
        let A = m ? b + x : g + v;
        if (u || !f && g <= 0) {
          const I = l;
          l += _, d.timelineStart = b;
          const L = a;
          a += x, i.push({
            event: d,
            start: b,
            end: A,
            playout: {
              start: L,
              end: a
            },
            integrated: {
              start: I,
              end: l
            }
          });
        } else if (g <= n) {
          if (!E) {
            const R = g - c;
            if (R > $p) {
              const D = c, M = l;
              l += R;
              const w = a;
              a += R;
              const N = {
                previousEvent: e[h - 1] || null,
                nextEvent: d,
                start: D,
                end: D + R,
                playout: {
                  start: w,
                  end: a
                },
                integrated: {
                  start: M,
                  end: l
                }
              };
              i.push(N);
            } else R > 0 && p && (p.cumulativeDuration += R, i[i.length - 1].end = g);
          }
          f && (A = b), d.timelineStart = b;
          const I = l;
          l += _;
          const L = a;
          a += x, i.push({
            event: d,
            start: b,
            end: A,
            playout: {
              start: L,
              end: a
            },
            integrated: {
              start: I,
              end: l
            }
          });
        } else
          return;
        const C = d.resumeTime;
        f || C > n ? c = n : c = C;
      }), c < n) {
        var o;
        const d = c, h = l, u = n - c;
        l += u;
        const f = a;
        a += u, i.push({
          previousEvent: ((o = i[i.length - 1]) == null ? void 0 : o.event) || null,
          nextEvent: null,
          start: c,
          end: d + u,
          playout: {
            start: f,
            end: a
          },
          integrated: {
            start: h,
            end: l
          }
        });
      }
      this.setDurations(n, a, l);
    } else
      i.push({
        previousEvent: null,
        nextEvent: null,
        start: 0,
        end: n,
        playout: {
          start: 0,
          end: n
        },
        integrated: {
          start: 0,
          end: n
        }
      }), this.setDurations(n, n, n);
    return i;
  }
  setDurations(e, t, i) {
    this.durations = {
      primary: e,
      playout: t,
      integrated: i
    };
  }
  resolveOffsets(e, t) {
    const i = t.main.details, s = i.live ? 1 / 0 : i.edge;
    let n = 0, a = -1;
    e.forEach((o, c) => {
      const l = o.cue.pre, d = o.cue.post, h = l ? 0 : d ? s : o.startTime;
      this.updateAssetDurations(o), a === h ? o.cumulativeDuration = n : (n = 0, a = h), !d && o.snapOptions.in && (o.resumeAnchor = Hs(null, i.fragments, o.startOffset + o.resumptionOffset, 0, 0) || void 0), o.appendInPlace && !o.appendInPlaceStarted && (this.primaryCanResumeInPlaceAt(o, t) || (o.appendInPlace = !1)), !o.appendInPlace && c + 1 < e.length && e[c + 1].startTime - e[c].resumeTime < $p && (e[c + 1].appendInPlace = !1, e[c + 1].appendInPlace && this.warn(`Could not change append strategy for abutting event ${o}`));
      const f = q(o.resumeOffset) ? o.resumeOffset : o.duration;
      n += f;
    });
  }
  primaryCanResumeInPlaceAt(e, t) {
    const i = e.resumeTime, s = e.startTime + e.resumptionOffset;
    return Math.abs(i - s) > Cr ? (this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`), !1) : !Object.keys(t).some((a) => {
      const o = t[a].details, c = o.edge;
      if (i >= c)
        return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${c}`), !1;
      const l = Hs(null, o.fragments, i);
      if (!l)
        return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`), !0;
      const d = a === "audio" ? 0.175 : 0;
      return Math.abs(l.start - i) < Cr + d || Math.abs(l.end - i) < Cr + d ? !1 : (this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`), !0);
    });
  }
  updateAssetDurations(e) {
    if (!e.assetListLoaded)
      return;
    const t = e.timelineStart;
    let i = 0, s = !1, n = !1;
    for (let a = 0; a < e.assetList.length; a++) {
      const o = e.assetList[a], c = t + i;
      o.startOffset = i, o.timelineStart = c, s || (s = o.duration === null), n || (n = !!o.error);
      const l = o.error ? 0 : o.duration || 0;
      i += l;
    }
    s && !n ? e.duration = Math.max(i, e.duration) : e.duration = i;
  }
  removeEvent(e) {
    e.reset(), delete this.eventMap[e.identifier];
  }
}
function ii(r) {
  return `[${r.event ? '"' + r.event.identifier + '"' : "primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`;
}
class EI {
  constructor(e) {
    this.hls = void 0, this.hls = e;
  }
  destroy() {
    this.hls = null;
  }
  loadAssetList(e, t) {
    const i = e.assetListUrl;
    let s;
    try {
      s = q_(i, this.hls.sessionId, e.baseUrl);
    } catch (u) {
      const f = this.assignAssetListError(e, V.ASSET_LIST_LOAD_ERROR, u, i);
      this.hls.trigger(T.ERROR, f);
      return;
    }
    t && s.protocol !== "data:" && s.searchParams.set("_HLS_start_offset", "" + t);
    const n = this.hls.config, a = n.loader, o = new a(n), c = {
      responseType: "json",
      url: s.href
    }, l = n.interstitialAssetListLoadPolicy.default, d = {
      loadPolicy: l,
      timeout: l.maxLoadTimeMs,
      maxRetry: 0,
      retryDelay: 0,
      maxRetryDelay: 0
    }, h = {
      onSuccess: (u, f, p, m) => {
        const g = u.data, x = g == null ? void 0 : g.ASSETS;
        if (!Array.isArray(x)) {
          const _ = this.assignAssetListError(e, V.ASSET_LIST_PARSING_ERROR, new Error("Invalid interstitial asset list"), p.url, f, m);
          this.hls.trigger(T.ERROR, _);
          return;
        }
        e.assetListResponse = g, this.hls.trigger(T.ASSET_LIST_LOADED, {
          event: e,
          assetListResponse: g,
          networkDetails: m
        });
      },
      onError: (u, f, p, m) => {
        const g = this.assignAssetListError(e, V.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`), f.url, m, p);
        this.hls.trigger(T.ERROR, g);
      },
      onTimeout: (u, f, p) => {
        const m = this.assignAssetListError(e, V.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${f.url})`), f.url, u, p);
        this.hls.trigger(T.ERROR, m);
      }
    };
    return o.load(c, d, h), this.hls.trigger(T.ASSET_LIST_LOADING, {
      event: e
    }), o;
  }
  assignAssetListError(e, t, i, s, n, a) {
    return e.error = i, {
      type: ie.NETWORK_ERROR,
      details: t,
      fatal: !1,
      interstitial: e,
      url: s,
      error: i,
      networkDetails: a,
      stats: n
    };
  }
}
function Kp(r) {
  r == null || r.play().catch(() => {
  });
}
function ra(r, e) {
  return `[${r}] Advancing timeline position to ${e}`;
}
class SI extends qt {
  constructor(e, t) {
    super("interstitials", e.logger), this.HlsPlayerClass = void 0, this.hls = void 0, this.assetListLoader = void 0, this.mediaSelection = null, this.altSelection = null, this.media = null, this.detachedData = null, this.requiredTracks = null, this.manager = null, this.playerQueue = [], this.bufferedPos = -1, this.timelinePos = -1, this.schedule = void 0, this.playingItem = null, this.bufferingItem = null, this.waitingItem = null, this.endedItem = null, this.playingAsset = null, this.endedAsset = null, this.bufferingAsset = null, this.shouldPlay = !1, this.onPlay = () => {
      this.shouldPlay = !0;
    }, this.onPause = () => {
      this.shouldPlay = !1;
    }, this.onSeeking = () => {
      const i = this.currentTime;
      if (i === void 0 || this.playbackDisabled || !this.schedule)
        return;
      const s = i - this.timelinePos;
      if (Math.abs(s) < 1 / 7056e5)
        return;
      const a = s <= -0.01;
      this.timelinePos = i, this.bufferedPos = i;
      const o = this.playingItem;
      if (!o) {
        this.checkBuffer();
        return;
      }
      if (a && this.schedule.resetErrorsInRange(i, i - s) && this.updateSchedule(!0), this.checkBuffer(), a && i < o.start || i >= o.end) {
        var c;
        const f = this.findItemIndex(o);
        let p = this.schedule.findItemIndexAtTime(i);
        if (p === -1 && (p = f + (a ? -1 : 1), this.log(`seeked ${a ? "back " : ""}to position not covered by schedule ${i} (resolving from ${f} to ${p})`)), !this.isInterstitial(o) && (c = this.media) != null && c.paused && (this.shouldPlay = !1), !a && p > f) {
          const m = this.schedule.findJumpRestrictedIndex(f + 1, p);
          if (m > f) {
            this.setSchedulePosition(m);
            return;
          }
        }
        this.setSchedulePosition(p);
        return;
      }
      const l = this.playingAsset;
      if (!l) {
        if (this.playingLastItem && this.isInterstitial(o)) {
          const f = o.event.assetList[0];
          f && (this.endedItem = this.playingItem, this.playingItem = null, this.setScheduleToAssetAtTime(i, f));
        }
        return;
      }
      const d = l.timelineStart, h = l.duration || 0;
      if (a && i < d || i >= d + h) {
        var u;
        (u = o.event) != null && u.appendInPlace && (this.clearInterstitial(o.event, o), this.flushFrontBuffer(i)), this.setScheduleToAssetAtTime(i, l);
      }
    }, this.onTimeupdate = () => {
      const i = this.currentTime;
      if (i === void 0 || this.playbackDisabled)
        return;
      if (i > this.timelinePos)
        this.timelinePos = i, i > this.bufferedPos && this.checkBuffer();
      else
        return;
      const s = this.playingItem;
      if (!s || this.playingLastItem)
        return;
      if (i >= s.end) {
        this.timelinePos = s.end;
        const o = this.findItemIndex(s);
        this.setSchedulePosition(o + 1);
      }
      const n = this.playingAsset;
      if (!n)
        return;
      const a = n.timelineStart + (n.duration || 0);
      i >= a && this.setScheduleToAssetAtTime(i, n);
    }, this.onScheduleUpdate = (i, s) => {
      const n = this.schedule;
      if (!n)
        return;
      const a = this.playingItem, o = n.events || [], c = n.items || [], l = n.durations, d = i.map((m) => m.identifier), h = !!(o.length || d.length);
      (h || s) && this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
Schedule: ${c.map((m) => ii(m))} pos: ${this.timelinePos}`), d.length && this.log(`Removed events ${d}`);
      let u = null, f = null;
      a && (u = this.updateItem(a, this.timelinePos), this.itemsMatch(a, u) ? this.playingItem = u : this.waitingItem = this.endedItem = null), this.waitingItem = this.updateItem(this.waitingItem), this.endedItem = this.updateItem(this.endedItem);
      const p = this.bufferingItem;
      if (p && (f = this.updateItem(p, this.bufferedPos), this.itemsMatch(p, f) ? this.bufferingItem = f : p.event && (this.bufferingItem = this.playingItem, this.clearInterstitial(p.event, null))), i.forEach((m) => {
        m.assetList.forEach((g) => {
          this.clearAssetPlayer(g.identifier, null);
        });
      }), this.playerQueue.forEach((m) => {
        if (m.interstitial.appendInPlace) {
          const g = m.assetItem.timelineStart, x = m.timelineOffset - g;
          if (x)
            try {
              m.timelineOffset = g;
            } catch (_) {
              Math.abs(x) > Cr && this.warn(`${_} ("${m.assetId}" ${m.timelineOffset}->${g})`);
            }
        }
      }), h || s) {
        if (this.hls.trigger(T.INTERSTITIALS_UPDATED, {
          events: o.slice(0),
          schedule: c.slice(0),
          durations: l,
          removedIds: d
        }), this.isInterstitial(a) && d.includes(a.event.identifier)) {
          this.warn(`Interstitial "${a.event.identifier}" removed while playing`), this.primaryFallback(a.event);
          return;
        }
        a && this.trimInPlace(u, a), p && f !== u && this.trimInPlace(f, p), this.checkBuffer();
      }
    }, this.hls = e, this.HlsPlayerClass = t, this.assetListLoader = new EI(e), this.schedule = new vI(this.onScheduleUpdate, e.logger), this.registerListeners();
  }
  registerListeners() {
    const e = this.hls;
    e && (e.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.on(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.on(T.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this), e.on(T.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this), e.on(T.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this), e.on(T.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this), e.on(T.ASSET_LIST_LOADED, this.onAssetListLoaded, this), e.on(T.BUFFER_APPENDED, this.onBufferAppended, this), e.on(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.on(T.BUFFERED_TO_END, this.onBufferedToEnd, this), e.on(T.MEDIA_ENDED, this.onMediaEnded, this), e.on(T.ERROR, this.onError, this), e.on(T.DESTROYING, this.onDestroying, this));
  }
  unregisterListeners() {
    const e = this.hls;
    e && (e.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.off(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.off(T.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this), e.off(T.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this), e.off(T.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this), e.off(T.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this), e.off(T.ASSET_LIST_LOADED, this.onAssetListLoaded, this), e.off(T.BUFFER_CODECS, this.onBufferCodecs, this), e.off(T.BUFFER_APPENDED, this.onBufferAppended, this), e.off(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.off(T.BUFFERED_TO_END, this.onBufferedToEnd, this), e.off(T.MEDIA_ENDED, this.onMediaEnded, this), e.off(T.ERROR, this.onError, this), e.off(T.DESTROYING, this.onDestroying, this));
  }
  startLoad() {
    this.resumeBuffering();
  }
  stopLoad() {
    this.pauseBuffering();
  }
  resumeBuffering() {
    var e;
    (e = this.getBufferingPlayer()) == null || e.resumeBuffering();
  }
  pauseBuffering() {
    var e;
    (e = this.getBufferingPlayer()) == null || e.pauseBuffering();
  }
  destroy() {
    this.unregisterListeners(), this.stopLoad(), this.assetListLoader && this.assetListLoader.destroy(), this.emptyPlayerQueue(), this.clearScheduleState(), this.schedule && this.schedule.destroy(), this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.schedule = this.manager = null, this.hls = this.HlsPlayerClass = this.log = null, this.assetListLoader = null, this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null, this.onScheduleUpdate = null;
  }
  onDestroying() {
    const e = this.primaryMedia || this.media;
    e && this.removeMediaListeners(e);
  }
  removeMediaListeners(e) {
    Ft(e, "play", this.onPlay), Ft(e, "pause", this.onPause), Ft(e, "seeking", this.onSeeking), Ft(e, "timeupdate", this.onTimeupdate);
  }
  onMediaAttaching(e, t) {
    const i = this.media = t.media;
    bt(i, "seeking", this.onSeeking), bt(i, "timeupdate", this.onTimeupdate), bt(i, "play", this.onPlay), bt(i, "pause", this.onPause);
  }
  onMediaAttached(e, t) {
    const i = this.effectivePlayingItem, s = this.detachedData;
    if (this.detachedData = null, i === null)
      this.checkStart();
    else if (!s) {
      this.clearScheduleState();
      const n = this.findItemIndex(i);
      this.setSchedulePosition(n);
    }
  }
  clearScheduleState() {
    this.log("clear schedule state"), this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  }
  onMediaDetaching(e, t) {
    const i = !!t.transferMedia, s = this.media;
    if (this.media = null, !i && (s && this.removeMediaListeners(s), this.detachedData)) {
      const n = this.getBufferingPlayer();
      n && (this.log(`Removing schedule state for detachedData and ${n}`), this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null, n.detachMedia()), this.shouldPlay = !1;
    }
  }
  get interstitialsManager() {
    if (!this.hls)
      return null;
    if (this.manager)
      return this.manager;
    const e = this, t = () => e.bufferingItem || e.waitingItem, i = (h) => h && e.getAssetPlayer(h.identifier), s = (h, u, f, p, m) => {
      if (h) {
        let g = h[u].start;
        const x = h.event;
        if (x) {
          if (u === "playout" || x.timelineOccupancy !== co.Point) {
            const _ = i(f);
            (_ == null ? void 0 : _.interstitial) === x && (g += _.assetItem.startOffset + _[m]);
          }
        } else {
          const _ = p === "bufferedPos" ? a() : e[p];
          g += _ - h.start;
        }
        return g;
      }
      return 0;
    }, n = (h, u) => {
      var f;
      if (h !== 0 && u !== "primary" && (f = e.schedule) != null && f.length) {
        var p;
        const m = e.schedule.findItemIndexAtTime(h), g = (p = e.schedule.items) == null ? void 0 : p[m];
        if (g) {
          const x = g[u].start - g.start;
          return h + x;
        }
      }
      return h;
    }, a = () => {
      const h = e.bufferedPos;
      return h === Number.MAX_VALUE ? o("primary") : Math.max(h, 0);
    }, o = (h) => {
      var u, f;
      return (u = e.primaryDetails) != null && u.live ? e.primaryDetails.edge : ((f = e.schedule) == null ? void 0 : f.durations[h]) || 0;
    }, c = (h, u) => {
      var f, p;
      const m = e.effectivePlayingItem;
      if (m != null && (f = m.event) != null && f.restrictions.skip || !e.schedule)
        return;
      e.log(`seek to ${h} "${u}"`);
      const g = e.effectivePlayingItem, x = e.schedule.findItemIndexAtTime(h, u), _ = (p = e.schedule.items) == null ? void 0 : p[x], v = e.getBufferingPlayer(), E = v == null ? void 0 : v.interstitial, b = E == null ? void 0 : E.appendInPlace, A = g && e.itemsMatch(g, _);
      if (g && (b || A)) {
        const C = i(e.playingAsset), I = (C == null ? void 0 : C.media) || e.primaryMedia;
        if (I) {
          const L = u === "primary" ? I.currentTime : s(g, u, e.playingAsset, "timelinePos", "currentTime"), R = h - L, D = (b ? L : I.currentTime) + R;
          if (D >= 0 && (!C || b || D <= C.duration)) {
            I.currentTime = D;
            return;
          }
        }
      }
      if (_) {
        let C = h;
        if (u !== "primary") {
          const L = _[u].start, R = h - L;
          C = _.start + R;
        }
        const I = !e.isInterstitial(_);
        if ((!e.isInterstitial(g) || g.event.appendInPlace) && (I || _.event.appendInPlace)) {
          const L = e.media || (b ? v == null ? void 0 : v.media : null);
          L && (L.currentTime = C);
        } else if (g) {
          const L = e.findItemIndex(g);
          if (x > L) {
            const D = e.schedule.findJumpRestrictedIndex(L + 1, x);
            if (D > L) {
              e.setSchedulePosition(D);
              return;
            }
          }
          let R = 0;
          if (I)
            e.timelinePos = C, e.checkBuffer();
          else {
            const D = _.event.assetList, M = h - (_[u] || _).start;
            for (let w = D.length; w--; ) {
              const N = D[w];
              if (N.duration && M >= N.startOffset && M < N.startOffset + N.duration) {
                R = w;
                break;
              }
            }
          }
          e.setSchedulePosition(x, R);
        }
      }
    }, l = () => {
      const h = e.effectivePlayingItem;
      if (e.isInterstitial(h))
        return h;
      const u = t();
      return e.isInterstitial(u) ? u : null;
    }, d = {
      get bufferedEnd() {
        const h = t(), u = e.bufferingItem;
        if (u && u === h) {
          var f;
          return s(u, "playout", e.bufferingAsset, "bufferedPos", "bufferedEnd") - u.playout.start || ((f = e.bufferingAsset) == null ? void 0 : f.startOffset) || 0;
        }
        return 0;
      },
      get currentTime() {
        const h = l(), u = e.effectivePlayingItem;
        return u && u === h ? s(u, "playout", e.effectivePlayingAsset, "timelinePos", "currentTime") - u.playout.start : 0;
      },
      set currentTime(h) {
        const u = l(), f = e.effectivePlayingItem;
        f && f === u && c(h + f.playout.start, "playout");
      },
      get duration() {
        const h = l();
        return h ? h.playout.end - h.playout.start : 0;
      },
      get assetPlayers() {
        var h;
        const u = (h = l()) == null ? void 0 : h.event.assetList;
        return u ? u.map((f) => e.getAssetPlayer(f.identifier)) : [];
      },
      get playingIndex() {
        var h;
        const u = (h = l()) == null ? void 0 : h.event;
        return u && e.effectivePlayingAsset ? u.findAssetIndex(e.effectivePlayingAsset) : -1;
      },
      get scheduleItem() {
        return l();
      }
    };
    return this.manager = {
      get events() {
        var h;
        return ((h = e.schedule) == null || (h = h.events) == null ? void 0 : h.slice(0)) || [];
      },
      get schedule() {
        var h;
        return ((h = e.schedule) == null || (h = h.items) == null ? void 0 : h.slice(0)) || [];
      },
      get interstitialPlayer() {
        return l() ? d : null;
      },
      get playerQueue() {
        return e.playerQueue.slice(0);
      },
      get bufferingAsset() {
        return e.bufferingAsset;
      },
      get bufferingItem() {
        return t();
      },
      get bufferingIndex() {
        const h = t();
        return e.findItemIndex(h);
      },
      get playingAsset() {
        return e.effectivePlayingAsset;
      },
      get playingItem() {
        return e.effectivePlayingItem;
      },
      get playingIndex() {
        const h = e.effectivePlayingItem;
        return e.findItemIndex(h);
      },
      primary: {
        get bufferedEnd() {
          return a();
        },
        get currentTime() {
          const h = e.timelinePos;
          return h > 0 ? h : 0;
        },
        set currentTime(h) {
          c(h, "primary");
        },
        get duration() {
          return o("primary");
        },
        get seekableStart() {
          var h;
          return ((h = e.primaryDetails) == null ? void 0 : h.fragmentStart) || 0;
        }
      },
      integrated: {
        get bufferedEnd() {
          return s(t(), "integrated", e.bufferingAsset, "bufferedPos", "bufferedEnd");
        },
        get currentTime() {
          return s(e.effectivePlayingItem, "integrated", e.effectivePlayingAsset, "timelinePos", "currentTime");
        },
        set currentTime(h) {
          c(h, "integrated");
        },
        get duration() {
          return o("integrated");
        },
        get seekableStart() {
          var h;
          return n(((h = e.primaryDetails) == null ? void 0 : h.fragmentStart) || 0, "integrated");
        }
      },
      skip: () => {
        const h = e.effectivePlayingItem, u = h == null ? void 0 : h.event;
        if (u && !u.restrictions.skip) {
          const f = e.findItemIndex(h);
          if (u.appendInPlace) {
            const p = h.playout.start + h.event.duration;
            c(p + 1e-3, "playout");
          } else
            e.advanceAfterAssetEnded(u, f, 1 / 0);
        }
      }
    };
  }
  // Schedule getters
  get effectivePlayingItem() {
    return this.waitingItem || this.playingItem || this.endedItem;
  }
  get effectivePlayingAsset() {
    return this.playingAsset || this.endedAsset;
  }
  get playingLastItem() {
    var e;
    const t = this.playingItem, i = (e = this.schedule) == null ? void 0 : e.items;
    return !this.playbackStarted || !t || !i ? !1 : this.findItemIndex(t) === i.length - 1;
  }
  get playbackStarted() {
    return this.effectivePlayingItem !== null;
  }
  // Media getters and event callbacks
  get currentTime() {
    var e, t;
    if (this.mediaSelection === null)
      return;
    const i = this.waitingItem || this.playingItem;
    if (this.isInterstitial(i) && !i.event.appendInPlace)
      return;
    let s = this.media;
    !s && (e = this.bufferingItem) != null && (e = e.event) != null && e.appendInPlace && (s = this.primaryMedia);
    const n = (t = s) == null ? void 0 : t.currentTime;
    if (!(n === void 0 || !q(n)))
      return n;
  }
  get primaryMedia() {
    var e;
    return this.media || ((e = this.detachedData) == null ? void 0 : e.media) || null;
  }
  isInterstitial(e) {
    return !!(e != null && e.event);
  }
  retreiveMediaSource(e, t) {
    const i = this.getAssetPlayer(e);
    i && this.transferMediaFromPlayer(i, t);
  }
  transferMediaFromPlayer(e, t) {
    const i = e.interstitial.appendInPlace, s = e.media;
    if (i && s === this.primaryMedia) {
      if (this.bufferingAsset = null, (!t || this.isInterstitial(t) && !t.event.appendInPlace) && t && s) {
        this.detachedData = {
          media: s
        };
        return;
      }
      const n = e.transferMedia();
      this.log(`transfer MediaSource from ${e} ${Ze(n)}`), this.detachedData = n;
    } else t && s && (this.shouldPlay || (this.shouldPlay = !s.paused));
  }
  transferMediaTo(e, t) {
    var i, s;
    if (e.media === t)
      return;
    let n = null;
    const a = this.hls, o = e !== a, c = o && e.interstitial.appendInPlace, l = (i = this.detachedData) == null ? void 0 : i.mediaSource;
    let d;
    if (a.media)
      c && (n = a.transferMedia(), this.detachedData = n), d = "Primary";
    else if (l) {
      const p = this.getBufferingPlayer();
      p ? (n = p.transferMedia(), d = `${p}`) : d = "detached MediaSource";
    } else
      d = "detached media";
    if (!n) {
      if (l)
        n = this.detachedData, this.log(`using detachedData: MediaSource ${Ze(n)}`);
      else if (!this.detachedData || a.media === t) {
        const p = this.playerQueue;
        p.length > 1 && p.forEach((m) => {
          if (o && m.interstitial.appendInPlace !== c) {
            const g = m.interstitial;
            this.clearInterstitial(m.interstitial, null), g.appendInPlace = !1, g.appendInPlace && this.warn(`Could not change append strategy for queued assets ${g}`);
          }
        }), this.hls.detachMedia(), this.detachedData = {
          media: t
        };
      }
    }
    const h = n && "mediaSource" in n && ((s = n.mediaSource) == null ? void 0 : s.readyState) !== "closed", u = h && n ? n : t;
    this.log(`${h ? "transfering MediaSource" : "attaching media"} to ${o ? e : "Primary"} from ${d} (media.currentTime: ${t.currentTime})`);
    const f = this.schedule;
    if (u === n && f) {
      const p = o && e.assetId === f.assetIdAtEnd;
      u.overrides = {
        duration: f.duration,
        endOfStream: !o || p,
        cueRemoval: !o
      };
    }
    e.attachMedia(u);
  }
  onInterstitialCueEnter() {
    this.onTimeupdate();
  }
  // Scheduling methods
  checkStart() {
    const e = this.schedule, t = e == null ? void 0 : e.events;
    if (!t || this.playbackDisabled || !this.media)
      return;
    this.bufferedPos === -1 && (this.bufferedPos = 0);
    const i = this.timelinePos, s = this.effectivePlayingItem;
    if (i === -1) {
      const n = this.hls.startPosition;
      if (this.log(ra("checkStart", n)), this.timelinePos = n, t.length && t[0].cue.pre) {
        const a = e.findEventIndex(t[0].identifier);
        this.setSchedulePosition(a);
      } else if (n >= 0 || !this.primaryLive) {
        const a = this.timelinePos = n > 0 ? n : 0, o = e.findItemIndexAtTime(a);
        this.setSchedulePosition(o);
      }
    } else if (s && !this.playingItem) {
      const n = e.findItemIndex(s);
      this.setSchedulePosition(n);
    }
  }
  advanceAssetBuffering(e, t) {
    const i = e.event, s = i.findAssetIndex(t), n = D0(i, s);
    if (!i.isAssetPastPlayoutLimit(n))
      this.bufferedToEvent(e, n);
    else if (this.schedule) {
      var a;
      const o = (a = this.schedule.items) == null ? void 0 : a[this.findItemIndex(e) + 1];
      o && this.bufferedToItem(o);
    }
  }
  advanceAfterAssetEnded(e, t, i) {
    const s = D0(e, i);
    if (e.isAssetPastPlayoutLimit(s)) {
      if (this.schedule) {
        const n = this.schedule.items;
        if (n) {
          const a = t + 1, o = n.length;
          if (a >= o) {
            this.setSchedulePosition(-1);
            return;
          }
          const c = e.resumeTime;
          this.timelinePos < c && (this.log(ra("advanceAfterAssetEnded", c)), this.timelinePos = c, e.appendInPlace && this.advanceInPlace(c), this.checkBuffer(this.bufferedPos < c)), this.setSchedulePosition(a);
        }
      }
    } else {
      if (e.appendInPlace) {
        const n = e.assetList[s];
        n && this.advanceInPlace(n.timelineStart);
      }
      this.setSchedulePosition(t, s);
    }
  }
  setScheduleToAssetAtTime(e, t) {
    const i = this.schedule;
    if (!i)
      return;
    const s = t.parentIdentifier, n = i.getEvent(s);
    if (n) {
      const a = i.findEventIndex(s), o = i.findAssetIndex(n, e);
      this.advanceAfterAssetEnded(n, a, o - 1);
    }
  }
  setSchedulePosition(e, t) {
    var i;
    const s = (i = this.schedule) == null ? void 0 : i.items;
    if (!s || this.playbackDisabled)
      return;
    const n = e >= 0 ? s[e] : null;
    this.log(`setSchedulePosition ${e}, ${t} (${n && ii(n)}) pos: ${this.timelinePos}`);
    const a = this.waitingItem || this.playingItem, o = this.playingLastItem;
    if (this.isInterstitial(a)) {
      const d = a.event, h = this.playingAsset, u = h == null ? void 0 : h.identifier, f = u ? this.getAssetPlayer(u) : null;
      if (f && u && (!this.eventItemsMatch(a, n) || t !== void 0 && u !== d.assetList[t].identifier)) {
        var c;
        const p = d.findAssetIndex(h);
        if (this.log(`INTERSTITIAL_ASSET_ENDED ${p + 1}/${d.assetList.length} ${dr(h)}`), this.endedAsset = h, this.playingAsset = null, this.hls.trigger(T.INTERSTITIAL_ASSET_ENDED, {
          asset: h,
          assetListIndex: p,
          event: d,
          schedule: s.slice(0),
          scheduleIndex: e,
          player: f
        }), a !== this.playingItem) {
          this.itemsMatch(a, this.playingItem) && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
          !this.playingAsset && this.advanceAfterAssetEnded(d, this.findItemIndex(this.playingItem), p);
          return;
        }
        this.retreiveMediaSource(u, n), f.media && !((c = this.detachedData) != null && c.mediaSource) && f.detachMedia();
      }
      if (!this.eventItemsMatch(a, n) && (this.endedItem = a, this.playingItem = null, this.log(`INTERSTITIAL_ENDED ${d} ${ii(a)}`), d.hasPlayed = !0, this.hls.trigger(T.INTERSTITIAL_ENDED, {
        event: d,
        schedule: s.slice(0),
        scheduleIndex: e
      }), d.cue.once)) {
        var l;
        this.updateSchedule();
        const p = (l = this.schedule) == null ? void 0 : l.items;
        if (n && p) {
          const m = this.findItemIndex(n);
          this.advanceSchedule(m, p, t, a, o);
        }
        return;
      }
    }
    this.advanceSchedule(e, s, t, a, o);
  }
  advanceSchedule(e, t, i, s, n) {
    const a = this.schedule;
    if (!a)
      return;
    const o = t[e] || null, c = this.primaryMedia, l = this.playerQueue;
    if (l.length && l.forEach((d) => {
      const h = d.interstitial, u = a.findEventIndex(h.identifier);
      (u < e || u > e + 1) && this.clearInterstitial(h, o);
    }), this.isInterstitial(o)) {
      this.timelinePos = Math.min(Math.max(this.timelinePos, o.start), o.end);
      const d = o.event;
      if (i === void 0) {
        i = a.findAssetIndex(d, this.timelinePos);
        const p = D0(d, i - 1);
        if (d.isAssetPastPlayoutLimit(p) || d.appendInPlace && this.timelinePos === o.end) {
          this.advanceAfterAssetEnded(d, e, i);
          return;
        }
        i = p;
      }
      const h = this.waitingItem;
      this.assetsBuffered(o, c) || this.setBufferingItem(o);
      let u = this.preloadAssets(d, i);
      if (this.eventItemsMatch(o, h || s) || (this.waitingItem = o, this.log(`INTERSTITIAL_STARTED ${ii(o)} ${d.appendInPlace ? "append in place" : ""}`), this.hls.trigger(T.INTERSTITIAL_STARTED, {
        event: d,
        schedule: t.slice(0),
        scheduleIndex: e
      })), !d.assetListLoaded) {
        this.log(`Waiting for ASSET-LIST to complete loading ${d}`);
        return;
      }
      if (d.assetListLoader && (d.assetListLoader.destroy(), d.assetListLoader = void 0), !c) {
        this.log(`Waiting for attachMedia to start Interstitial ${d}`);
        return;
      }
      this.waitingItem = this.endedItem = null, this.playingItem = o;
      const f = d.assetList[i];
      if (!f) {
        this.advanceAfterAssetEnded(d, e, i || 0);
        return;
      }
      if (u || (u = this.getAssetPlayer(f.identifier)), u === null || u.destroyed) {
        const p = d.assetList.length;
        this.warn(`asset ${i + 1}/${p} player destroyed ${d}`), u = this.createAssetPlayer(d, f, i), u.loadSource();
      }
      if (!this.eventItemsMatch(o, this.bufferingItem) && d.appendInPlace && this.isAssetBuffered(f))
        return;
      this.startAssetPlayer(u, i, t, e, c), this.shouldPlay && Kp(u.media);
    } else o ? (this.resumePrimary(o, e, s), this.shouldPlay && Kp(this.hls.media)) : n && this.isInterstitial(s) && (this.endedItem = null, this.playingItem = s, s.event.appendInPlace || this.attachPrimary(a.durations.primary, null));
  }
  get playbackDisabled() {
    return this.hls.config.enableInterstitialPlayback === !1;
  }
  get primaryDetails() {
    var e;
    return (e = this.mediaSelection) == null ? void 0 : e.main.details;
  }
  get primaryLive() {
    var e;
    return !!((e = this.primaryDetails) != null && e.live);
  }
  resumePrimary(e, t, i) {
    var s, n;
    if (this.playingItem = e, this.playingAsset = this.endedAsset = null, this.waitingItem = this.endedItem = null, this.bufferedToItem(e), this.log(`resuming ${ii(e)}`), !((s = this.detachedData) != null && s.mediaSource)) {
      let o = this.timelinePos;
      (o < e.start || o >= e.end) && (o = this.getPrimaryResumption(e, t), this.log(ra("resumePrimary", o)), this.timelinePos = o), this.attachPrimary(o, e);
    }
    if (!i)
      return;
    const a = (n = this.schedule) == null ? void 0 : n.items;
    a && (this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ii(e)}`), this.hls.trigger(T.INTERSTITIALS_PRIMARY_RESUMED, {
      schedule: a.slice(0),
      scheduleIndex: t
    }), this.checkBuffer());
  }
  getPrimaryResumption(e, t) {
    const i = e.start;
    if (this.primaryLive) {
      const s = this.primaryDetails;
      if (t === 0)
        return this.hls.startPosition;
      if (s && (i < s.fragmentStart || i > s.edge))
        return this.hls.liveSyncPosition || -1;
    }
    return i;
  }
  isAssetBuffered(e) {
    const t = this.getAssetPlayer(e.identifier);
    return t != null && t.hls ? t.hls.bufferedToEnd : ce.bufferInfo(this.primaryMedia, this.timelinePos, 0).end + 1 >= e.timelineStart + (e.duration || 0);
  }
  attachPrimary(e, t, i) {
    t ? this.setBufferingItem(t) : this.bufferingItem = this.playingItem, this.bufferingAsset = null;
    const s = this.primaryMedia;
    if (!s)
      return;
    const n = this.hls;
    n.media ? this.checkBuffer() : (this.transferMediaTo(n, s), i && this.startLoadingPrimaryAt(e, i)), i || (this.log(ra("attachPrimary", e)), this.timelinePos = e, this.startLoadingPrimaryAt(e, i));
  }
  startLoadingPrimaryAt(e, t) {
    var i;
    const s = this.hls;
    !s.loadingEnabled || !s.media || Math.abs((((i = s.mainForwardBufferInfo) == null ? void 0 : i.start) || s.media.currentTime) - e) > 0.5 ? s.startLoad(e, t) : s.bufferingEnabled || s.resumeBuffering();
  }
  // HLS.js event callbacks
  onManifestLoading() {
    var e;
    this.stopLoad(), (e = this.schedule) == null || e.reset(), this.emptyPlayerQueue(), this.clearScheduleState(), this.shouldPlay = !1, this.bufferedPos = this.timelinePos = -1, this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null, this.hls.off(T.BUFFER_CODECS, this.onBufferCodecs, this), this.hls.on(T.BUFFER_CODECS, this.onBufferCodecs, this);
  }
  onLevelUpdated(e, t) {
    if (t.level === -1 || !this.schedule)
      return;
    const i = this.hls.levels[t.level], s = we(we({}, this.mediaSelection || this.altSelection), {}, {
      main: i
    });
    this.mediaSelection = s, this.schedule.parseInterstitialDateRanges(s, this.hls.config.interstitialAppendInPlace), !this.effectivePlayingItem && this.schedule.items && this.checkStart();
  }
  onAudioTrackUpdated(e, t) {
    const i = this.hls.audioTracks[t.id], s = this.mediaSelection;
    if (!s) {
      this.altSelection = we(we({}, this.altSelection), {}, {
        audio: i
      });
      return;
    }
    const n = we(we({}, s), {}, {
      audio: i
    });
    this.mediaSelection = n;
  }
  onSubtitleTrackUpdated(e, t) {
    const i = this.hls.subtitleTracks[t.id], s = this.mediaSelection;
    if (!s) {
      this.altSelection = we(we({}, this.altSelection), {}, {
        subtitles: i
      });
      return;
    }
    const n = we(we({}, s), {}, {
      subtitles: i
    });
    this.mediaSelection = n;
  }
  onAudioTrackSwitching(e, t) {
    const i = sp(t);
    this.playerQueue.forEach(({
      hls: s
    }) => s && (s.setAudioOption(t) || s.setAudioOption(i)));
  }
  onSubtitleTrackSwitch(e, t) {
    const i = sp(t);
    this.playerQueue.forEach(({
      hls: s
    }) => s && (s.setSubtitleOption(t) || t.id !== -1 && s.setSubtitleOption(i)));
  }
  onBufferCodecs(e, t) {
    const i = t.tracks;
    i && (this.requiredTracks = i);
  }
  onBufferAppended(e, t) {
    this.checkBuffer();
  }
  onBufferFlushed(e, t) {
    const i = this.playingItem;
    if (i && !this.itemsMatch(i, this.bufferingItem) && !this.isInterstitial(i)) {
      const s = this.timelinePos;
      this.bufferedPos = s, this.checkBuffer();
    }
  }
  onBufferedToEnd(e) {
    if (!this.schedule)
      return;
    const t = this.schedule.events;
    if (this.bufferedPos < Number.MAX_VALUE && t) {
      for (let s = 0; s < t.length; s++) {
        const n = t[s];
        if (n.cue.post) {
          var i;
          const a = this.schedule.findEventIndex(n.identifier), o = (i = this.schedule.items) == null ? void 0 : i[a];
          this.isInterstitial(o) && this.eventItemsMatch(o, this.bufferingItem) && this.bufferedToItem(o, 0);
          break;
        }
      }
      this.bufferedPos = Number.MAX_VALUE;
    }
  }
  onMediaEnded(e) {
    const t = this.playingItem;
    if (!this.playingLastItem && t) {
      const i = this.findItemIndex(t);
      this.setSchedulePosition(i + 1);
    } else
      this.shouldPlay = !1;
  }
  updateItem(e, t) {
    var i;
    const s = (i = this.schedule) == null ? void 0 : i.items;
    if (e && s) {
      const n = this.findItemIndex(e, t);
      return s[n] || null;
    }
    return null;
  }
  trimInPlace(e, t) {
    if (this.isInterstitial(e) && e.event.appendInPlace && t.end - e.end > 0.25) {
      e.event.assetList.forEach((n, a) => {
        e.event.isAssetPastPlayoutLimit(a) && this.clearAssetPlayer(n.identifier, null);
      });
      const i = e.end + 0.25, s = ce.bufferInfo(this.primaryMedia, i, 0);
      (s.end > i || (s.nextStart || 0) > i) && (this.log(`trim buffered interstitial ${ii(e)} (was ${ii(t)})`), this.attachPrimary(i, null, !0), this.flushFrontBuffer(i));
    }
  }
  itemsMatch(e, t) {
    return !!t && (e === t || e.event && t.event && this.eventItemsMatch(e, t) || !e.event && !t.event && this.findItemIndex(e) === this.findItemIndex(t));
  }
  eventItemsMatch(e, t) {
    var i;
    return !!t && (e === t || e.event.identifier === ((i = t.event) == null ? void 0 : i.identifier));
  }
  findItemIndex(e, t) {
    return e && this.schedule ? this.schedule.findItemIndex(e, t) : -1;
  }
  updateSchedule(e = !1) {
    var t;
    const i = this.mediaSelection;
    i && ((t = this.schedule) == null || t.updateSchedule(i, [], e));
  }
  // Schedule buffer control
  checkBuffer(e) {
    var t;
    const i = (t = this.schedule) == null ? void 0 : t.items;
    if (!i)
      return;
    const s = ce.bufferInfo(this.primaryMedia, this.timelinePos, 0);
    e && (this.bufferedPos = this.timelinePos), e || (e = s.len < 1), this.updateBufferedPos(s.end, i, e);
  }
  updateBufferedPos(e, t, i) {
    const s = this.schedule, n = this.bufferingItem;
    if (this.bufferedPos > e || !s)
      return;
    if (t.length === 1 && this.itemsMatch(t[0], n)) {
      this.bufferedPos = e;
      return;
    }
    const a = this.playingItem, o = this.findItemIndex(a);
    let c = s.findItemIndexAtTime(e);
    if (this.bufferedPos < e) {
      var l;
      const d = this.findItemIndex(n), h = Math.min(d + 1, t.length - 1), u = t[h];
      if ((c === -1 && n && e >= n.end || (l = u.event) != null && l.appendInPlace && e + 0.01 >= u.start) && (c = h), this.isInterstitial(n)) {
        const f = n.event;
        if (h - o > 1 && f.appendInPlace === !1 || f.assetList.length === 0 && f.assetListLoader)
          return;
      }
      if (this.bufferedPos = e, c > d && c > o)
        this.bufferedToItem(u);
      else {
        const f = this.primaryDetails;
        this.primaryLive && f && e > f.edge - f.targetduration && u.start < f.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(u) && this.preloadAssets(u.event, 0);
      }
    } else i && a && !this.itemsMatch(a, n) && (c === o ? this.bufferedToItem(a) : c === o + 1 && this.bufferedToItem(t[c]));
  }
  assetsBuffered(e, t) {
    return e.event.assetList.length === 0 ? !1 : !e.event.assetList.some((s) => {
      const n = this.getAssetPlayer(s.identifier);
      return !(n != null && n.bufferedInPlaceToEnd(t));
    });
  }
  setBufferingItem(e) {
    const t = this.bufferingItem, i = this.schedule;
    if (!this.itemsMatch(e, t) && i) {
      const {
        items: s,
        events: n
      } = i;
      if (!s || !n)
        return t;
      const a = this.isInterstitial(e), o = this.getBufferingPlayer();
      this.bufferingItem = e, this.bufferedPos = Math.max(e.start, Math.min(e.end, this.timelinePos));
      const c = o ? o.remaining : t ? t.end - this.timelinePos : 0;
      if (this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ii(e)}` + (t ? ` (${c.toFixed(2)} remaining)` : "")), !this.playbackDisabled)
        if (a) {
          const l = i.findAssetIndex(e.event, this.bufferedPos);
          e.event.assetList.forEach((d, h) => {
            const u = this.getAssetPlayer(d.identifier);
            u && (h === l && u.loadSource(), u.resumeBuffering());
          });
        } else
          this.hls.resumeBuffering(), this.playerQueue.forEach((l) => l.pauseBuffering());
      this.hls.trigger(T.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
        events: n.slice(0),
        schedule: s.slice(0),
        bufferingIndex: this.findItemIndex(e),
        playingIndex: this.findItemIndex(this.playingItem)
      });
    } else this.bufferingItem !== e && (this.bufferingItem = e);
    return t;
  }
  bufferedToItem(e, t = 0) {
    const i = this.setBufferingItem(e);
    if (!this.playbackDisabled) {
      if (this.isInterstitial(e))
        this.bufferedToEvent(e, t);
      else if (i !== null) {
        this.bufferingAsset = null;
        const s = this.detachedData;
        s ? s.mediaSource ? this.attachPrimary(e.start, e, !0) : this.preloadPrimary(e) : this.preloadPrimary(e);
      }
    }
  }
  preloadPrimary(e) {
    const t = this.findItemIndex(e), i = this.getPrimaryResumption(e, t);
    this.startLoadingPrimaryAt(i);
  }
  bufferedToEvent(e, t) {
    const i = e.event, s = i.assetList.length === 0 && !i.assetListLoader, n = i.cue.once;
    if (s || !n) {
      const a = this.preloadAssets(i, t);
      if (a != null && a.interstitial.appendInPlace) {
        const o = this.primaryMedia;
        o && this.bufferAssetPlayer(a, o);
      }
    }
  }
  preloadAssets(e, t) {
    const i = e.assetUrl, s = e.assetList.length, n = s === 0 && !e.assetListLoader, a = e.cue.once;
    if (n) {
      const c = e.timelineStart;
      if (e.appendInPlace) {
        var o;
        const u = this.playingItem;
        !this.isInterstitial(u) && (u == null || (o = u.nextEvent) == null ? void 0 : o.identifier) === e.identifier && this.flushFrontBuffer(c + 0.25);
      }
      let l, d = 0;
      if (!this.playingItem && this.primaryLive && (d = this.hls.startPosition, d === -1 && (d = this.hls.liveSyncPosition || 0)), d && !(e.cue.pre || e.cue.post)) {
        const u = d - c;
        u > 0 && (l = Math.round(u * 1e3) / 1e3);
      }
      if (this.log(`Load interstitial asset ${t + 1}/${i ? 1 : s} ${e}${l ? ` live-start: ${d} start-offset: ${l}` : ""}`), i)
        return this.createAsset(e, 0, 0, c, e.duration, i);
      const h = this.assetListLoader.loadAssetList(e, l);
      h && (e.assetListLoader = h);
    } else if (!a && s) {
      for (let l = t; l < s; l++) {
        const d = e.assetList[l], h = this.getAssetPlayerQueueIndex(d.identifier);
        (h === -1 || this.playerQueue[h].destroyed) && !d.error && this.createAssetPlayer(e, d, l);
      }
      const c = e.assetList[t];
      if (c) {
        const l = this.getAssetPlayer(c.identifier);
        return l && l.loadSource(), l;
      }
    }
    return null;
  }
  flushFrontBuffer(e) {
    const t = this.requiredTracks;
    if (!t)
      return;
    this.log(`Removing front buffer starting at ${e}`), Object.keys(t).forEach((s) => {
      this.hls.trigger(T.BUFFER_FLUSHING, {
        startOffset: e,
        endOffset: 1 / 0,
        type: s
      });
    });
  }
  // Interstitial Asset Player control
  getAssetPlayerQueueIndex(e) {
    const t = this.playerQueue;
    for (let i = 0; i < t.length; i++)
      if (e === t[i].assetId)
        return i;
    return -1;
  }
  getAssetPlayer(e) {
    const t = this.getAssetPlayerQueueIndex(e);
    return this.playerQueue[t] || null;
  }
  getBufferingPlayer() {
    const {
      playerQueue: e,
      primaryMedia: t
    } = this;
    if (t) {
      for (let i = 0; i < e.length; i++)
        if (e[i].media === t)
          return e[i];
    }
    return null;
  }
  createAsset(e, t, i, s, n, a) {
    const o = {
      parentIdentifier: e.identifier,
      identifier: gI(e, a, t),
      duration: n,
      startOffset: i,
      timelineStart: s,
      uri: a
    };
    return this.createAssetPlayer(e, o, t);
  }
  createAssetPlayer(e, t, i) {
    const s = this.hls, n = s.userConfig;
    let a = n.videoPreference;
    const o = s.loadLevelObj || s.levels[s.currentLevel];
    (a || o) && (a = Me({}, a), o.videoCodec && (a.videoCodec = o.videoCodec), o.videoRange && (a.allowedVideoRanges = [o.videoRange]));
    const c = s.audioTracks[s.audioTrack], l = s.subtitleTracks[s.subtitleTrack];
    let d = 0;
    if (this.primaryLive || e.appendInPlace) {
      const E = this.timelinePos - t.timelineStart;
      if (E > 1) {
        const b = t.duration;
        b && E < b && (d = E);
      }
    }
    const h = t.identifier, u = we(we({}, n), {}, {
      maxMaxBufferLength: Math.min(180, s.config.maxMaxBufferLength),
      autoStartLoad: !0,
      startFragPrefetch: !0,
      primarySessionId: s.sessionId,
      assetPlayerId: h,
      abrEwmaDefaultEstimate: s.bandwidthEstimate,
      interstitialsController: void 0,
      startPosition: d,
      liveDurationInfinity: !1,
      testBandwidth: !1,
      videoPreference: a,
      audioPreference: c || n.audioPreference,
      subtitlePreference: l || n.subtitlePreference
    });
    e.appendInPlace && (e.appendInPlaceStarted = !0, t.timelineStart && (u.timelineOffset = t.timelineStart));
    const f = u.cmcd;
    f != null && f.sessionId && f.contentId && (u.cmcd = Me({}, f, {
      contentId: dn(t.uri)
    })), this.getAssetPlayer(h) && this.warn(`Duplicate date range identifier ${e} and asset ${h}`);
    const p = new xI(this.HlsPlayerClass, u, e, t);
    this.playerQueue.push(p), e.assetList[i] = t;
    let m = !0;
    const g = (E) => {
      if (E.live) {
        var b;
        const I = new Error(`Interstitials MUST be VOD assets ${e}`), L = {
          fatal: !0,
          type: ie.OTHER_ERROR,
          details: V.INTERSTITIAL_ASSET_ITEM_ERROR,
          error: I
        }, R = ((b = this.schedule) == null ? void 0 : b.findEventIndex(e.identifier)) || -1;
        this.handleAssetItemError(L, e, R, i, I.message);
        return;
      }
      const A = E.edge - E.fragmentStart, C = t.duration;
      (m || C === null || A > C) && (m = !1, this.log(`Interstitial asset "${h}" duration change ${C} > ${A}`), t.duration = A, this.updateSchedule());
    };
    p.on(T.LEVEL_UPDATED, (E, {
      details: b
    }) => g(b)), p.on(T.LEVEL_PTS_UPDATED, (E, {
      details: b
    }) => g(b)), p.on(T.EVENT_CUE_ENTER, () => this.onInterstitialCueEnter());
    const x = (E, b) => {
      const A = this.getAssetPlayer(h);
      if (A && b.tracks) {
        A.off(T.BUFFER_CODECS, x), A.tracks = b.tracks;
        const C = this.primaryMedia;
        this.bufferingAsset === A.assetItem && C && !A.media && this.bufferAssetPlayer(A, C);
      }
    };
    p.on(T.BUFFER_CODECS, x);
    const _ = () => {
      var E;
      const b = this.getAssetPlayer(h);
      if (this.log(`buffered to end of asset ${b}`), !b || !this.schedule)
        return;
      const A = this.schedule.findEventIndex(e.identifier), C = (E = this.schedule.items) == null ? void 0 : E[A];
      this.isInterstitial(C) && this.advanceAssetBuffering(C, t);
    };
    p.on(T.BUFFERED_TO_END, _);
    const v = (E) => () => {
      if (!this.getAssetPlayer(h) || !this.schedule)
        return;
      this.shouldPlay = !0;
      const A = this.schedule.findEventIndex(e.identifier);
      this.advanceAfterAssetEnded(e, A, E);
    };
    return p.once(T.MEDIA_ENDED, v(i)), p.once(T.PLAYOUT_LIMIT_REACHED, v(1 / 0)), p.on(T.ERROR, (E, b) => {
      if (!this.schedule)
        return;
      const A = this.getAssetPlayer(h);
      if (b.details === V.BUFFER_STALLED_ERROR) {
        if (A != null && A.appendInPlace) {
          this.handleInPlaceStall(e);
          return;
        }
        this.onTimeupdate(), this.checkBuffer(!0);
        return;
      }
      this.handleAssetItemError(b, e, this.schedule.findEventIndex(e.identifier), i, `Asset player error ${b.error} ${e}`);
    }), p.on(T.DESTROYING, () => {
      if (!this.getAssetPlayer(h) || !this.schedule)
        return;
      const b = new Error(`Asset player destroyed unexpectedly ${h}`), A = {
        fatal: !0,
        type: ie.OTHER_ERROR,
        details: V.INTERSTITIAL_ASSET_ITEM_ERROR,
        error: b
      };
      this.handleAssetItemError(A, e, this.schedule.findEventIndex(e.identifier), i, b.message);
    }), this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${dr(t)}`), this.hls.trigger(T.INTERSTITIAL_ASSET_PLAYER_CREATED, {
      asset: t,
      assetListIndex: i,
      event: e,
      player: p
    }), p;
  }
  clearInterstitial(e, t) {
    e.assetList.forEach((i) => {
      this.clearAssetPlayer(i.identifier, t);
    }), e.reset();
  }
  resetAssetPlayer(e) {
    const t = this.getAssetPlayerQueueIndex(e);
    if (t !== -1) {
      this.log(`reset asset player "${e}" after error`);
      const i = this.playerQueue[t];
      this.transferMediaFromPlayer(i, null), i.resetDetails();
    }
  }
  clearAssetPlayer(e, t) {
    const i = this.getAssetPlayerQueueIndex(e);
    if (i !== -1) {
      const s = this.playerQueue[i];
      this.log(`clear ${s} toSegment: ${t && ii(t)}`), this.transferMediaFromPlayer(s, t), this.playerQueue.splice(i, 1), s.destroy();
    }
  }
  emptyPlayerQueue() {
    let e;
    for (; e = this.playerQueue.pop(); )
      e.destroy();
    this.playerQueue = [];
  }
  startAssetPlayer(e, t, i, s, n) {
    const {
      interstitial: a,
      assetItem: o,
      assetId: c
    } = e, l = a.assetList.length, d = this.playingAsset;
    this.endedAsset = null, this.playingAsset = o, (!d || d.identifier !== c) && (d && (this.clearAssetPlayer(d.identifier, i[s]), delete d.error), this.log(`INTERSTITIAL_ASSET_STARTED ${t + 1}/${l} ${dr(o)}`), this.hls.trigger(T.INTERSTITIAL_ASSET_STARTED, {
      asset: o,
      assetListIndex: t,
      event: a,
      schedule: i.slice(0),
      scheduleIndex: s,
      player: e
    })), this.bufferAssetPlayer(e, n);
  }
  bufferAssetPlayer(e, t) {
    var i, s;
    if (!this.schedule)
      return;
    const {
      interstitial: n,
      assetItem: a
    } = e, o = this.schedule.findEventIndex(n.identifier), c = (i = this.schedule.items) == null ? void 0 : i[o];
    if (!c)
      return;
    e.loadSource(), this.setBufferingItem(c), this.bufferingAsset = a;
    const l = this.getBufferingPlayer();
    if (l === e)
      return;
    const d = n.appendInPlace;
    if (d && (l == null ? void 0 : l.interstitial.appendInPlace) === !1)
      return;
    const h = (l == null ? void 0 : l.tracks) || ((s = this.detachedData) == null ? void 0 : s.tracks) || this.requiredTracks;
    if (d && a !== this.playingAsset) {
      if (!e.tracks) {
        this.log(`Waiting for track info before buffering ${e}`);
        return;
      }
      if (h && !Ug(h, e.tracks)) {
        const u = new Error(`Asset ${dr(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`), f = {
          fatal: !0,
          type: ie.OTHER_ERROR,
          details: V.INTERSTITIAL_ASSET_ITEM_ERROR,
          error: u
        }, p = n.findAssetIndex(a);
        this.handleAssetItemError(f, n, o, p, u.message);
        return;
      }
    }
    this.transferMediaTo(e, t);
  }
  handleInPlaceStall(e) {
    const t = this.schedule, i = this.primaryMedia;
    if (!t || !i)
      return;
    const s = i.currentTime, n = t.findAssetIndex(e, s), a = e.assetList[n];
    if (a) {
      const o = this.getAssetPlayer(a.identifier);
      if (o) {
        const c = o.currentTime || s - a.timelineStart, l = o.duration - c;
        if (this.warn(`Stalled at ${c} of ${c + l} in ${o} ${e} (media.currentTime: ${s})`), c && (l / i.playbackRate < 0.5 || o.bufferedInPlaceToEnd(i)) && o.hls) {
          const d = t.findEventIndex(e.identifier);
          this.advanceAfterAssetEnded(e, d, n);
        }
      }
    }
  }
  advanceInPlace(e) {
    const t = this.primaryMedia;
    t && t.currentTime < e && (t.currentTime = e);
  }
  handleAssetItemError(e, t, i, s, n) {
    if (e.details === V.BUFFER_STALLED_ERROR)
      return;
    const a = t.assetList[s] || null;
    if (this.warn(`INTERSTITIAL_ASSET_ERROR ${a && dr(a)} ${e.error}`), !this.schedule)
      return;
    const o = (a == null ? void 0 : a.identifier) || "", c = this.getAssetPlayerQueueIndex(o), l = this.playerQueue[c] || null, d = this.schedule.items, h = Me({}, e, {
      fatal: !1,
      errorAction: Tr(!0),
      asset: a,
      assetListIndex: s,
      event: t,
      schedule: d,
      scheduleIndex: i,
      player: l
    });
    if (this.hls.trigger(T.INTERSTITIAL_ASSET_ERROR, h), !e.fatal)
      return;
    const u = this.playingAsset, f = this.bufferingAsset, p = new Error(n);
    if (a && (this.clearAssetPlayer(o, null), a.error = p), !t.assetList.some((m) => !m.error))
      t.error = p;
    else
      for (let m = s; m < t.assetList.length; m++)
        this.resetAssetPlayer(t.assetList[m].identifier);
    this.updateSchedule(!0), t.error ? this.primaryFallback(t) : u && u.identifier === o ? this.advanceAfterAssetEnded(t, i, s) : f && f.identifier === o && this.isInterstitial(this.bufferingItem) && this.advanceAssetBuffering(this.bufferingItem, f);
  }
  primaryFallback(e) {
    const t = e.timelineStart, i = this.effectivePlayingItem;
    if (i) {
      this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${ii(i)} error: ${e.error}`);
      let s = this.timelinePos;
      s === -1 && (s = this.hls.startPosition);
      const n = this.updateItem(i, s);
      if (this.itemsMatch(i, n) && this.clearInterstitial(e, null), e.appendInPlace && (this.attachPrimary(t, null), this.flushFrontBuffer(t)), !this.schedule)
        return;
      const a = this.schedule.findItemIndexAtTime(s);
      this.setSchedulePosition(a);
    } else
      this.checkStart();
  }
  // Asset List loading
  onAssetListLoaded(e, t) {
    var i, s;
    const n = t.event, a = n.identifier, o = t.assetListResponse.ASSETS;
    if (!((i = this.schedule) != null && i.hasEvent(a)))
      return;
    const c = n.timelineStart, l = n.duration;
    let d = 0;
    o.forEach((m, g) => {
      const x = parseFloat(m.DURATION);
      this.createAsset(n, g, d, c + d, x, m.URI), d += x;
    }), n.duration = d, this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${n}`);
    const h = this.waitingItem, u = (h == null ? void 0 : h.event.identifier) === a;
    this.updateSchedule();
    const f = (s = this.bufferingItem) == null ? void 0 : s.event;
    if (u) {
      var p;
      const m = this.schedule.findEventIndex(a), g = (p = this.schedule.items) == null ? void 0 : p[m];
      if (g) {
        if (!this.playingItem && this.timelinePos > g.end && this.schedule.findItemIndexAtTime(this.timelinePos) !== m) {
          n.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`), this.updateSchedule(!0), this.primaryFallback(n);
          return;
        }
        this.setBufferingItem(g);
      }
      this.setSchedulePosition(m);
    } else if ((f == null ? void 0 : f.identifier) === a) {
      const m = n.assetList[0];
      if (m) {
        const g = this.getAssetPlayer(m.identifier);
        if (f.appendInPlace) {
          const x = this.primaryMedia;
          g && x && this.bufferAssetPlayer(g, x);
        } else g && g.loadSource();
      }
    }
  }
  onError(e, t) {
    if (this.schedule)
      switch (t.details) {
        case V.ASSET_LIST_PARSING_ERROR:
        case V.ASSET_LIST_LOAD_ERROR:
        case V.ASSET_LIST_LOAD_TIMEOUT: {
          const i = t.interstitial;
          i && (this.updateSchedule(!0), this.primaryFallback(i));
          break;
        }
        case V.BUFFER_STALLED_ERROR: {
          const i = this.endedItem || this.waitingItem || this.playingItem;
          if (this.isInterstitial(i) && i.event.appendInPlace) {
            this.handleInPlaceStall(i.event);
            return;
          }
          this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`), this.onTimeupdate(), this.checkBuffer(!0);
          break;
        }
      }
  }
}
const Xp = 500;
class TI extends Yd {
  constructor(e, t, i) {
    super(e, t, i, "subtitle-stream-controller", te.SUBTITLE), this.currentTrackId = -1, this.tracksBuffered = [], this.mainDetails = null, this.registerListeners();
  }
  onHandlerDestroying() {
    this.unregisterListeners(), super.onHandlerDestroying(), this.mainDetails = null;
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls: e
    } = this;
    e.on(T.LEVEL_LOADED, this.onLevelLoaded, this), e.on(T.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this), e.on(T.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this), e.on(T.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this), e.on(T.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this), e.on(T.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  unregisterListeners() {
    super.unregisterListeners();
    const {
      hls: e
    } = this;
    e.off(T.LEVEL_LOADED, this.onLevelLoaded, this), e.off(T.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this), e.off(T.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this), e.off(T.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this), e.off(T.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this), e.off(T.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  startLoad(e, t) {
    this.stopLoad(), this.state = K.IDLE, this.setInterval(Xp), this.nextLoadPosition = this.lastCurrentTime = e + this.timelineOffset, this.startPosition = t ? -1 : e, this.tick();
  }
  onManifestLoading() {
    super.onManifestLoading(), this.mainDetails = null;
  }
  onMediaDetaching(e, t) {
    this.tracksBuffered = [], super.onMediaDetaching(e, t);
  }
  onLevelLoaded(e, t) {
    this.mainDetails = t.details;
  }
  onSubtitleFragProcessed(e, t) {
    const {
      frag: i,
      success: s
    } = t;
    if (this.fragContextChanged(i) || (et(i) && (this.fragPrevious = i), this.state = K.IDLE), !s)
      return;
    const n = this.tracksBuffered[this.currentTrackId];
    if (!n)
      return;
    let a;
    const o = i.start;
    for (let l = 0; l < n.length; l++)
      if (o >= n[l].start && o <= n[l].end) {
        a = n[l];
        break;
      }
    const c = i.start + i.duration;
    a ? a.end = c : (a = {
      start: o,
      end: c
    }, n.push(a)), this.fragmentTracker.fragBuffered(i), this.fragBufferedComplete(i, null), this.media && this.tick();
  }
  onBufferFlushing(e, t) {
    const {
      startOffset: i,
      endOffset: s
    } = t;
    if (i === 0 && s !== Number.POSITIVE_INFINITY) {
      const n = s - 1;
      if (n <= 0)
        return;
      t.endOffsetSubtitles = Math.max(0, n), this.tracksBuffered.forEach((a) => {
        for (let o = 0; o < a.length; ) {
          if (a[o].end <= n) {
            a.shift();
            continue;
          } else if (a[o].start < n)
            a[o].start = n;
          else
            break;
          o++;
        }
      }), this.fragmentTracker.removeFragmentsInRange(i, n, te.SUBTITLE);
    }
  }
  // If something goes wrong, proceed to next frag, if we were processing one.
  onError(e, t) {
    const i = t.frag;
    (i == null ? void 0 : i.type) === te.SUBTITLE && (t.details === V.FRAG_GAP && this.fragmentTracker.fragBuffered(i, !0), this.fragCurrent && this.fragCurrent.abortRequests(), this.state !== K.STOPPED && (this.state = K.IDLE));
  }
  // Got all new subtitle levels.
  onSubtitleTracksUpdated(e, {
    subtitleTracks: t
  }) {
    if (this.levels && N_(this.levels, t)) {
      this.levels = t.map((i) => new En(i));
      return;
    }
    this.tracksBuffered = [], this.levels = t.map((i) => {
      const s = new En(i);
      return this.tracksBuffered[s.id] = [], s;
    }), this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, te.SUBTITLE), this.fragPrevious = null, this.mediaBuffer = null;
  }
  onSubtitleTrackSwitch(e, t) {
    var i;
    if (this.currentTrackId = t.id, !((i = this.levels) != null && i.length) || this.currentTrackId === -1) {
      this.clearInterval();
      return;
    }
    const s = this.levels[this.currentTrackId];
    s != null && s.details ? this.mediaBuffer = this.mediaBufferTimeRanges : this.mediaBuffer = null, s && this.state !== K.STOPPED && this.setInterval(Xp);
  }
  // Got a new set of subtitle fragments.
  onSubtitleTrackLoaded(e, t) {
    var i;
    const {
      currentTrackId: s,
      levels: n
    } = this, {
      details: a,
      id: o
    } = t;
    if (!n) {
      this.warn(`Subtitle tracks were reset while loading level ${o}`);
      return;
    }
    const c = n[o];
    if (o >= n.length || !c)
      return;
    this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn ? `[part-${a.lastPartSn}-${a.lastPartIndex}]` : ""},duration:${a.totalduration}`), this.mediaBuffer = this.mediaBufferTimeRanges;
    let l = 0;
    if (a.live || (i = c.details) != null && i.live) {
      if (a.deltaUpdateFailed)
        return;
      const h = this.mainDetails;
      if (!h) {
        this.startFragRequested = !1;
        return;
      }
      const u = h.fragments[0];
      if (!c.details)
        a.hasProgramDateTime && h.hasProgramDateTime ? (oo(a, h), l = a.fragmentStart) : u && (l = u.start, Fc(a, l));
      else {
        var d;
        l = this.alignPlaylists(a, c.details, (d = this.levelLastLoaded) == null ? void 0 : d.details), l === 0 && u && (l = u.start, Fc(a, l));
      }
      h && !this.startFragRequested && this.setStartPosition(h, l);
    }
    c.details = a, this.levelLastLoaded = c, o === s && (this.hls.trigger(T.SUBTITLE_TRACK_UPDATED, {
      details: a,
      id: o,
      groupId: t.groupId
    }), this.tick(), a.live && !this.fragCurrent && this.media && this.state === K.IDLE && (Hs(null, a.fragments, this.media.currentTime, 0) || (this.warn("Subtitle playlist not aligned with playback"), c.details = void 0)));
  }
  _handleFragmentLoadComplete(e) {
    const {
      frag: t,
      payload: i
    } = e, s = t.decryptdata, n = this.hls;
    if (!this.fragContextChanged(t) && i && i.byteLength > 0 && s != null && s.key && s.iv && br(s.method)) {
      const a = performance.now();
      this.decrypter.decrypt(new Uint8Array(i), s.key.buffer, s.iv.buffer, Kd(s.method)).catch((o) => {
        throw n.trigger(T.ERROR, {
          type: ie.MEDIA_ERROR,
          details: V.FRAG_DECRYPT_ERROR,
          fatal: !1,
          error: o,
          reason: o.message,
          frag: t
        }), o;
      }).then((o) => {
        const c = performance.now();
        n.trigger(T.FRAG_DECRYPTED, {
          frag: t,
          payload: o,
          stats: {
            tstart: a,
            tdecrypt: c
          }
        });
      }).catch((o) => {
        this.warn(`${o.name}: ${o.message}`), this.state = K.IDLE;
      });
    }
  }
  doTick() {
    if (!this.media) {
      this.state = K.IDLE;
      return;
    }
    if (this.state === K.IDLE) {
      const {
        currentTrackId: e,
        levels: t
      } = this, i = t == null ? void 0 : t[e];
      if (!i || !t.length || !i.details || this.waitForLive(i))
        return;
      const {
        config: s
      } = this, n = this.getLoadPosition(), a = ce.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], n, s.maxBufferHole), {
        end: o,
        len: c
      } = a, l = i.details, d = this.hls.maxBufferLength + l.levelTargetDuration;
      if (c > d)
        return;
      const h = l.fragments, u = h.length, f = l.edge;
      let p = null;
      const m = this.fragPrevious;
      if (o < f) {
        const _ = s.maxFragLookUpTolerance, v = o > f - _ ? 0 : _;
        p = Hs(m, h, Math.max(h[0].start, o), v), !p && m && m.start < h[0].start && (p = h[0]);
      } else
        p = h[u - 1];
      if (p = this.filterReplacedPrimary(p, i.details), !p)
        return;
      const g = p.sn - l.startSN, x = h[g - 1];
      if (x && x.cc === p.cc && this.fragmentTracker.getState(x) === nt.NOT_LOADED && (p = x), this.fragmentTracker.getState(p) === nt.NOT_LOADED) {
        const _ = this.mapToInitFragWhenRequired(p);
        _ && this.loadFragment(_, i, o);
      }
    }
  }
  loadFragment(e, t, i) {
    et(e) ? super.loadFragment(e, t, i) : this._loadInitSegment(e, t);
  }
  get mediaBufferTimeRanges() {
    return new bI(this.tracksBuffered[this.currentTrackId] || []);
  }
}
class bI {
  constructor(e) {
    this.buffered = void 0;
    const t = (i, s, n) => {
      if (s = s >>> 0, s > n - 1)
        throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);
      return e[s][i];
    };
    this.buffered = {
      get length() {
        return e.length;
      },
      end(i) {
        return t("end", i, e.length);
      },
      start(i) {
        return t("start", i, e.length);
      }
    };
  }
}
const AI = {
  42: 225,
  // lowercase a, acute accent
  92: 233,
  // lowercase e, acute accent
  94: 237,
  // lowercase i, acute accent
  95: 243,
  // lowercase o, acute accent
  96: 250,
  // lowercase u, acute accent
  123: 231,
  // lowercase c with cedilla
  124: 247,
  // division symbol
  125: 209,
  // uppercase N tilde
  126: 241,
  // lowercase n tilde
  127: 9608,
  // Full block
  // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  128: 174,
  // Registered symbol (R)
  129: 176,
  // degree sign
  130: 189,
  // 1/2 symbol
  131: 191,
  // Inverted (open) question mark
  132: 8482,
  // Trademark symbol (TM)
  133: 162,
  // Cents symbol
  134: 163,
  // Pounds sterling
  135: 9834,
  // Music 8'th note
  136: 224,
  // lowercase a, grave accent
  137: 32,
  // transparent space (regular)
  138: 232,
  // lowercase e, grave accent
  139: 226,
  // lowercase a, circumflex accent
  140: 234,
  // lowercase e, circumflex accent
  141: 238,
  // lowercase i, circumflex accent
  142: 244,
  // lowercase o, circumflex accent
  143: 251,
  // lowercase u, circumflex accent
  // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  144: 193,
  // capital letter A with acute
  145: 201,
  // capital letter E with acute
  146: 211,
  // capital letter O with acute
  147: 218,
  // capital letter U with acute
  148: 220,
  // capital letter U with diaresis
  149: 252,
  // lowercase letter U with diaeresis
  150: 8216,
  // opening single quote
  151: 161,
  // inverted exclamation mark
  152: 42,
  // asterisk
  153: 8217,
  // closing single quote
  154: 9473,
  // box drawings heavy horizontal
  155: 169,
  // copyright sign
  156: 8480,
  // Service mark
  157: 8226,
  // (round) bullet
  158: 8220,
  // Left double quotation mark
  159: 8221,
  // Right double quotation mark
  160: 192,
  // uppercase A, grave accent
  161: 194,
  // uppercase A, circumflex
  162: 199,
  // uppercase C with cedilla
  163: 200,
  // uppercase E, grave accent
  164: 202,
  // uppercase E, circumflex
  165: 203,
  // capital letter E with diaresis
  166: 235,
  // lowercase letter e with diaresis
  167: 206,
  // uppercase I, circumflex
  168: 207,
  // uppercase I, with diaresis
  169: 239,
  // lowercase i, with diaresis
  170: 212,
  // uppercase O, circumflex
  171: 217,
  // uppercase U, grave accent
  172: 249,
  // lowercase u, grave accent
  173: 219,
  // uppercase U, circumflex
  174: 171,
  // left-pointing double angle quotation mark
  175: 187,
  // right-pointing double angle quotation mark
  // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  176: 195,
  // Uppercase A, tilde
  177: 227,
  // Lowercase a, tilde
  178: 205,
  // Uppercase I, acute accent
  179: 204,
  // Uppercase I, grave accent
  180: 236,
  // Lowercase i, grave accent
  181: 210,
  // Uppercase O, grave accent
  182: 242,
  // Lowercase o, grave accent
  183: 213,
  // Uppercase O, tilde
  184: 245,
  // Lowercase o, tilde
  185: 123,
  // Open curly brace
  186: 125,
  // Closing curly brace
  187: 92,
  // Backslash
  188: 94,
  // Caret
  189: 95,
  // Underscore
  190: 124,
  // Pipe (vertical line)
  191: 8764,
  // Tilde operator
  192: 196,
  // Uppercase A, umlaut
  193: 228,
  // Lowercase A, umlaut
  194: 214,
  // Uppercase O, umlaut
  195: 246,
  // Lowercase o, umlaut
  196: 223,
  // Esszett (sharp S)
  197: 165,
  // Yen symbol
  198: 164,
  // Generic currency sign
  199: 9475,
  // Box drawings heavy vertical
  200: 197,
  // Uppercase A, ring
  201: 229,
  // Lowercase A, ring
  202: 216,
  // Uppercase O, stroke
  203: 248,
  // Lowercase o, strok
  204: 9487,
  // Box drawings heavy down and right
  205: 9491,
  // Box drawings heavy down and left
  206: 9495,
  // Box drawings heavy up and right
  207: 9499
  // Box drawings heavy up and left
}, ey = (r) => String.fromCharCode(AI[r] || r), ai = 15, Gi = 100, CI = {
  17: 1,
  18: 3,
  21: 5,
  22: 7,
  23: 9,
  16: 11,
  19: 12,
  20: 14
}, RI = {
  17: 2,
  18: 4,
  21: 6,
  22: 8,
  23: 10,
  19: 13,
  20: 15
}, II = {
  25: 1,
  26: 3,
  29: 5,
  30: 7,
  31: 9,
  24: 11,
  27: 12,
  28: 14
}, LI = {
  25: 2,
  26: 4,
  29: 6,
  30: 8,
  31: 10,
  27: 13,
  28: 15
}, DI = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"];
class PI {
  constructor() {
    this.time = null, this.verboseLevel = 0;
  }
  log(e, t) {
    if (this.verboseLevel >= e) {
      const i = typeof t == "function" ? t() : t;
      Pe.log(`${this.time} [${e}] ${i}`);
    }
  }
}
const Cs = function(e) {
  const t = [];
  for (let i = 0; i < e.length; i++)
    t.push(e[i].toString(16));
  return t;
};
class ty {
  constructor() {
    this.foreground = "white", this.underline = !1, this.italics = !1, this.background = "black", this.flash = !1;
  }
  reset() {
    this.foreground = "white", this.underline = !1, this.italics = !1, this.background = "black", this.flash = !1;
  }
  setStyles(e) {
    const t = ["foreground", "underline", "italics", "background", "flash"];
    for (let i = 0; i < t.length; i++) {
      const s = t[i];
      e.hasOwnProperty(s) && (this[s] = e[s]);
    }
  }
  isDefault() {
    return this.foreground === "white" && !this.underline && !this.italics && this.background === "black" && !this.flash;
  }
  equals(e) {
    return this.foreground === e.foreground && this.underline === e.underline && this.italics === e.italics && this.background === e.background && this.flash === e.flash;
  }
  copy(e) {
    this.foreground = e.foreground, this.underline = e.underline, this.italics = e.italics, this.background = e.background, this.flash = e.flash;
  }
  toString() {
    return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash;
  }
}
class kI {
  constructor() {
    this.uchar = " ", this.penState = new ty();
  }
  reset() {
    this.uchar = " ", this.penState.reset();
  }
  setChar(e, t) {
    this.uchar = e, this.penState.copy(t);
  }
  setPenState(e) {
    this.penState.copy(e);
  }
  equals(e) {
    return this.uchar === e.uchar && this.penState.equals(e.penState);
  }
  copy(e) {
    this.uchar = e.uchar, this.penState.copy(e.penState);
  }
  isEmpty() {
    return this.uchar === " " && this.penState.isDefault();
  }
}
class wI {
  constructor(e) {
    this.chars = [], this.pos = 0, this.currPenState = new ty(), this.cueStartTime = null, this.logger = void 0;
    for (let t = 0; t < Gi; t++)
      this.chars.push(new kI());
    this.logger = e;
  }
  equals(e) {
    for (let t = 0; t < Gi; t++)
      if (!this.chars[t].equals(e.chars[t]))
        return !1;
    return !0;
  }
  copy(e) {
    for (let t = 0; t < Gi; t++)
      this.chars[t].copy(e.chars[t]);
  }
  isEmpty() {
    let e = !0;
    for (let t = 0; t < Gi; t++)
      if (!this.chars[t].isEmpty()) {
        e = !1;
        break;
      }
    return e;
  }
  /**
   *  Set the cursor to a valid column.
   */
  setCursor(e) {
    this.pos !== e && (this.pos = e), this.pos < 0 ? (this.logger.log(3, "Negative cursor position " + this.pos), this.pos = 0) : this.pos > Gi && (this.logger.log(3, "Too large cursor position " + this.pos), this.pos = Gi);
  }
  /**
   * Move the cursor relative to current position.
   */
  moveCursor(e) {
    const t = this.pos + e;
    if (e > 1)
      for (let i = this.pos + 1; i < t + 1; i++)
        this.chars[i].setPenState(this.currPenState);
    this.setCursor(t);
  }
  /**
   * Backspace, move one step back and clear character.
   */
  backSpace() {
    this.moveCursor(-1), this.chars[this.pos].setChar(" ", this.currPenState);
  }
  insertChar(e) {
    e >= 144 && this.backSpace();
    const t = ey(e);
    if (this.pos >= Gi) {
      this.logger.log(0, () => "Cannot insert " + e.toString(16) + " (" + t + ") at position " + this.pos + ". Skipping it!");
      return;
    }
    this.chars[this.pos].setChar(t, this.currPenState), this.moveCursor(1);
  }
  clearFromPos(e) {
    let t;
    for (t = e; t < Gi; t++)
      this.chars[t].reset();
  }
  clear() {
    this.clearFromPos(0), this.pos = 0, this.currPenState.reset();
  }
  clearToEndOfRow() {
    this.clearFromPos(this.pos);
  }
  getTextString() {
    const e = [];
    let t = !0;
    for (let i = 0; i < Gi; i++) {
      const s = this.chars[i].uchar;
      s !== " " && (t = !1), e.push(s);
    }
    return t ? "" : e.join("");
  }
  setPenStyles(e) {
    this.currPenState.setStyles(e), this.chars[this.pos].setPenState(this.currPenState);
  }
}
class P0 {
  constructor(e) {
    this.rows = [], this.currRow = ai - 1, this.nrRollUpRows = null, this.lastOutputScreen = null, this.logger = void 0;
    for (let t = 0; t < ai; t++)
      this.rows.push(new wI(e));
    this.logger = e;
  }
  reset() {
    for (let e = 0; e < ai; e++)
      this.rows[e].clear();
    this.currRow = ai - 1;
  }
  equals(e) {
    let t = !0;
    for (let i = 0; i < ai; i++)
      if (!this.rows[i].equals(e.rows[i])) {
        t = !1;
        break;
      }
    return t;
  }
  copy(e) {
    for (let t = 0; t < ai; t++)
      this.rows[t].copy(e.rows[t]);
  }
  isEmpty() {
    let e = !0;
    for (let t = 0; t < ai; t++)
      if (!this.rows[t].isEmpty()) {
        e = !1;
        break;
      }
    return e;
  }
  backSpace() {
    this.rows[this.currRow].backSpace();
  }
  clearToEndOfRow() {
    this.rows[this.currRow].clearToEndOfRow();
  }
  /**
   * Insert a character (without styling) in the current row.
   */
  insertChar(e) {
    this.rows[this.currRow].insertChar(e);
  }
  setPen(e) {
    this.rows[this.currRow].setPenStyles(e);
  }
  moveCursor(e) {
    this.rows[this.currRow].moveCursor(e);
  }
  setCursor(e) {
    this.logger.log(2, "setCursor: " + e), this.rows[this.currRow].setCursor(e);
  }
  setPAC(e) {
    this.logger.log(2, () => "pacData = " + Ze(e));
    let t = e.row - 1;
    if (this.nrRollUpRows && t < this.nrRollUpRows - 1 && (t = this.nrRollUpRows - 1), this.nrRollUpRows && this.currRow !== t) {
      for (let o = 0; o < ai; o++)
        this.rows[o].clear();
      const n = this.currRow + 1 - this.nrRollUpRows, a = this.lastOutputScreen;
      if (a) {
        const o = a.rows[n].cueStartTime, c = this.logger.time;
        if (o !== null && c !== null && o < c)
          for (let l = 0; l < this.nrRollUpRows; l++)
            this.rows[t - this.nrRollUpRows + l + 1].copy(a.rows[n + l]);
      }
    }
    this.currRow = t;
    const i = this.rows[this.currRow];
    if (e.indent !== null) {
      const n = e.indent, a = Math.max(n - 1, 0);
      i.setCursor(e.indent), e.color = i.chars[a].penState.foreground;
    }
    const s = {
      foreground: e.color,
      underline: e.underline,
      italics: e.italics,
      background: "black",
      flash: !1
    };
    this.setPen(s);
  }
  /**
   * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
   */
  setBkgData(e) {
    this.logger.log(2, () => "bkgData = " + Ze(e)), this.backSpace(), this.setPen(e), this.insertChar(32);
  }
  setRollUpRows(e) {
    this.nrRollUpRows = e;
  }
  rollUp() {
    if (this.nrRollUpRows === null) {
      this.logger.log(3, "roll_up but nrRollUpRows not set yet");
      return;
    }
    this.logger.log(1, () => this.getDisplayText());
    const e = this.currRow + 1 - this.nrRollUpRows, t = this.rows.splice(e, 1)[0];
    t.clear(), this.rows.splice(this.currRow, 0, t), this.logger.log(2, "Rolling up");
  }
  /**
   * Get all non-empty rows with as unicode text.
   */
  getDisplayText(e) {
    e = e || !1;
    const t = [];
    let i = "", s = -1;
    for (let n = 0; n < ai; n++) {
      const a = this.rows[n].getTextString();
      a && (s = n + 1, e ? t.push("Row " + s + ": '" + a + "'") : t.push(a.trim()));
    }
    return t.length > 0 && (e ? i = "[" + t.join(" | ") + "]" : i = t.join(`
`)), i;
  }
  getTextAndFormat() {
    return this.rows;
  }
}
class Yp {
  constructor(e, t, i) {
    this.chNr = void 0, this.outputFilter = void 0, this.mode = void 0, this.verbose = void 0, this.displayedMemory = void 0, this.nonDisplayedMemory = void 0, this.lastOutputScreen = void 0, this.currRollUpRow = void 0, this.writeScreen = void 0, this.cueStartTime = void 0, this.logger = void 0, this.chNr = e, this.outputFilter = t, this.mode = null, this.verbose = 0, this.displayedMemory = new P0(i), this.nonDisplayedMemory = new P0(i), this.lastOutputScreen = new P0(i), this.currRollUpRow = this.displayedMemory.rows[ai - 1], this.writeScreen = this.displayedMemory, this.mode = null, this.cueStartTime = null, this.logger = i;
  }
  reset() {
    this.mode = null, this.displayedMemory.reset(), this.nonDisplayedMemory.reset(), this.lastOutputScreen.reset(), this.outputFilter.reset(), this.currRollUpRow = this.displayedMemory.rows[ai - 1], this.writeScreen = this.displayedMemory, this.mode = null, this.cueStartTime = null;
  }
  getHandler() {
    return this.outputFilter;
  }
  setHandler(e) {
    this.outputFilter = e;
  }
  setPAC(e) {
    this.writeScreen.setPAC(e);
  }
  setBkgData(e) {
    this.writeScreen.setBkgData(e);
  }
  setMode(e) {
    e !== this.mode && (this.mode = e, this.logger.log(2, () => "MODE=" + e), this.mode === "MODE_POP-ON" ? this.writeScreen = this.nonDisplayedMemory : (this.writeScreen = this.displayedMemory, this.writeScreen.reset()), this.mode !== "MODE_ROLL-UP" && (this.displayedMemory.nrRollUpRows = null, this.nonDisplayedMemory.nrRollUpRows = null), this.mode = e);
  }
  insertChars(e) {
    for (let i = 0; i < e.length; i++)
      this.writeScreen.insertChar(e[i]);
    const t = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP";
    this.logger.log(2, () => t + ": " + this.writeScreen.getDisplayText(!0)), (this.mode === "MODE_PAINT-ON" || this.mode === "MODE_ROLL-UP") && (this.logger.log(1, () => "DISPLAYED: " + this.displayedMemory.getDisplayText(!0)), this.outputDataUpdate());
  }
  ccRCL() {
    this.logger.log(2, "RCL - Resume Caption Loading"), this.setMode("MODE_POP-ON");
  }
  ccBS() {
    this.logger.log(2, "BS - BackSpace"), this.mode !== "MODE_TEXT" && (this.writeScreen.backSpace(), this.writeScreen === this.displayedMemory && this.outputDataUpdate());
  }
  ccAOF() {
  }
  ccAON() {
  }
  ccDER() {
    this.logger.log(2, "DER- Delete to End of Row"), this.writeScreen.clearToEndOfRow(), this.outputDataUpdate();
  }
  ccRU(e) {
    this.logger.log(2, "RU(" + e + ") - Roll Up"), this.writeScreen = this.displayedMemory, this.setMode("MODE_ROLL-UP"), this.writeScreen.setRollUpRows(e);
  }
  ccFON() {
    this.logger.log(2, "FON - Flash On"), this.writeScreen.setPen({
      flash: !0
    });
  }
  ccRDC() {
    this.logger.log(2, "RDC - Resume Direct Captioning"), this.setMode("MODE_PAINT-ON");
  }
  ccTR() {
    this.logger.log(2, "TR"), this.setMode("MODE_TEXT");
  }
  ccRTD() {
    this.logger.log(2, "RTD"), this.setMode("MODE_TEXT");
  }
  ccEDM() {
    this.logger.log(2, "EDM - Erase Displayed Memory"), this.displayedMemory.reset(), this.outputDataUpdate(!0);
  }
  ccCR() {
    this.logger.log(2, "CR - Carriage Return"), this.writeScreen.rollUp(), this.outputDataUpdate(!0);
  }
  ccENM() {
    this.logger.log(2, "ENM - Erase Non-displayed Memory"), this.nonDisplayedMemory.reset();
  }
  ccEOC() {
    if (this.logger.log(2, "EOC - End Of Caption"), this.mode === "MODE_POP-ON") {
      const e = this.displayedMemory;
      this.displayedMemory = this.nonDisplayedMemory, this.nonDisplayedMemory = e, this.writeScreen = this.nonDisplayedMemory, this.logger.log(1, () => "DISP: " + this.displayedMemory.getDisplayText());
    }
    this.outputDataUpdate(!0);
  }
  ccTO(e) {
    this.logger.log(2, "TO(" + e + ") - Tab Offset"), this.writeScreen.moveCursor(e);
  }
  ccMIDROW(e) {
    const t = {
      flash: !1
    };
    if (t.underline = e % 2 === 1, t.italics = e >= 46, t.italics)
      t.foreground = "white";
    else {
      const i = Math.floor(e / 2) - 16, s = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"];
      t.foreground = s[i];
    }
    this.logger.log(2, "MIDROW: " + Ze(t)), this.writeScreen.setPen(t);
  }
  outputDataUpdate(e = !1) {
    const t = this.logger.time;
    t !== null && this.outputFilter && (this.cueStartTime === null && !this.displayedMemory.isEmpty() ? this.cueStartTime = t : this.displayedMemory.equals(this.lastOutputScreen) || (this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen), e && this.outputFilter.dispatchCue && this.outputFilter.dispatchCue(), this.cueStartTime = this.displayedMemory.isEmpty() ? null : t), this.lastOutputScreen.copy(this.displayedMemory));
  }
  cueSplitAtTime(e) {
    this.outputFilter && (this.displayedMemory.isEmpty() || (this.outputFilter.newCue && this.outputFilter.newCue(this.cueStartTime, e, this.displayedMemory), this.cueStartTime = e));
  }
}
class zp {
  constructor(e, t, i) {
    this.channels = void 0, this.currentChannel = 0, this.cmdHistory = BI(), this.logger = void 0;
    const s = this.logger = new PI();
    this.channels = [null, new Yp(e, t, s), new Yp(e + 1, i, s)];
  }
  getHandler(e) {
    return this.channels[e].getHandler();
  }
  setHandler(e, t) {
    this.channels[e].setHandler(t);
  }
  /**
   * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
   */
  addData(e, t) {
    this.logger.time = e;
    for (let i = 0; i < t.length; i += 2) {
      const s = t[i] & 127, n = t[i + 1] & 127;
      let a = !1, o = null;
      if (s === 0 && n === 0)
        continue;
      this.logger.log(3, () => "[" + Cs([t[i], t[i + 1]]) + "] -> (" + Cs([s, n]) + ")");
      const c = this.cmdHistory;
      if (s >= 16 && s <= 31) {
        if (MI(s, n, c)) {
          na(null, null, c), this.logger.log(3, () => "Repeated command (" + Cs([s, n]) + ") is dropped");
          continue;
        }
        na(s, n, this.cmdHistory), a = this.parseCmd(s, n), a || (a = this.parseMidrow(s, n)), a || (a = this.parsePAC(s, n)), a || (a = this.parseBackgroundAttributes(s, n));
      } else
        na(null, null, c);
      if (!a && (o = this.parseChars(s, n), o)) {
        const d = this.currentChannel;
        d && d > 0 ? this.channels[d].insertChars(o) : this.logger.log(2, "No channel found yet. TEXT-MODE?");
      }
      !a && !o && this.logger.log(2, () => "Couldn't parse cleaned data " + Cs([s, n]) + " orig: " + Cs([t[i], t[i + 1]]));
    }
  }
  /**
   * Parse Command.
   * @returns True if a command was found
   */
  parseCmd(e, t) {
    const i = (e === 20 || e === 28 || e === 21 || e === 29) && t >= 32 && t <= 47, s = (e === 23 || e === 31) && t >= 33 && t <= 35;
    if (!(i || s))
      return !1;
    const n = e === 20 || e === 21 || e === 23 ? 1 : 2, a = this.channels[n];
    return e === 20 || e === 21 || e === 28 || e === 29 ? t === 32 ? a.ccRCL() : t === 33 ? a.ccBS() : t === 34 ? a.ccAOF() : t === 35 ? a.ccAON() : t === 36 ? a.ccDER() : t === 37 ? a.ccRU(2) : t === 38 ? a.ccRU(3) : t === 39 ? a.ccRU(4) : t === 40 ? a.ccFON() : t === 41 ? a.ccRDC() : t === 42 ? a.ccTR() : t === 43 ? a.ccRTD() : t === 44 ? a.ccEDM() : t === 45 ? a.ccCR() : t === 46 ? a.ccENM() : t === 47 && a.ccEOC() : a.ccTO(t - 32), this.currentChannel = n, !0;
  }
  /**
   * Parse midrow styling command
   */
  parseMidrow(e, t) {
    let i = 0;
    if ((e === 17 || e === 25) && t >= 32 && t <= 47) {
      if (e === 17 ? i = 1 : i = 2, i !== this.currentChannel)
        return this.logger.log(0, "Mismatch channel in midrow parsing"), !1;
      const s = this.channels[i];
      return s ? (s.ccMIDROW(t), this.logger.log(3, () => "MIDROW (" + Cs([e, t]) + ")"), !0) : !1;
    }
    return !1;
  }
  /**
   * Parse Preable Access Codes (Table 53).
   * @returns {Boolean} Tells if PAC found
   */
  parsePAC(e, t) {
    let i;
    const s = (e >= 17 && e <= 23 || e >= 25 && e <= 31) && t >= 64 && t <= 127, n = (e === 16 || e === 24) && t >= 64 && t <= 95;
    if (!(s || n))
      return !1;
    const a = e <= 23 ? 1 : 2;
    t >= 64 && t <= 95 ? i = a === 1 ? CI[e] : II[e] : i = a === 1 ? RI[e] : LI[e];
    const o = this.channels[a];
    return o ? (o.setPAC(this.interpretPAC(i, t)), this.currentChannel = a, !0) : !1;
  }
  /**
   * Interpret the second byte of the pac, and return the information.
   * @returns pacData with style parameters
   */
  interpretPAC(e, t) {
    let i;
    const s = {
      color: null,
      italics: !1,
      indent: null,
      underline: !1,
      row: e
    };
    return t > 95 ? i = t - 96 : i = t - 64, s.underline = (i & 1) === 1, i <= 13 ? s.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(i / 2)] : i <= 15 ? (s.italics = !0, s.color = "white") : s.indent = Math.floor((i - 16) / 2) * 4, s;
  }
  /**
   * Parse characters.
   * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
   */
  parseChars(e, t) {
    let i, s = null, n = null;
    if (e >= 25 ? (i = 2, n = e - 8) : (i = 1, n = e), n >= 17 && n <= 19) {
      let a;
      n === 17 ? a = t + 80 : n === 18 ? a = t + 112 : a = t + 144, this.logger.log(2, () => "Special char '" + ey(a) + "' in channel " + i), s = [a];
    } else e >= 32 && e <= 127 && (s = t === 0 ? [e] : [e, t]);
    return s && this.logger.log(3, () => "Char codes =  " + Cs(s).join(",")), s;
  }
  /**
   * Parse extended background attributes as well as new foreground color black.
   * @returns True if background attributes are found
   */
  parseBackgroundAttributes(e, t) {
    const i = (e === 16 || e === 24) && t >= 32 && t <= 47, s = (e === 23 || e === 31) && t >= 45 && t <= 47;
    if (!(i || s))
      return !1;
    let n;
    const a = {};
    e === 16 || e === 24 ? (n = Math.floor((t - 32) / 2), a.background = DI[n], t % 2 === 1 && (a.background = a.background + "_semi")) : t === 45 ? a.background = "transparent" : (a.foreground = "black", t === 47 && (a.underline = !0));
    const o = e <= 23 ? 1 : 2;
    return this.channels[o].setBkgData(a), !0;
  }
  /**
   * Reset state of parser and its channels.
   */
  reset() {
    for (let e = 0; e < Object.keys(this.channels).length; e++) {
      const t = this.channels[e];
      t && t.reset();
    }
    na(null, null, this.cmdHistory);
  }
  /**
   * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
   */
  cueSplitAtTime(e) {
    for (let t = 0; t < this.channels.length; t++) {
      const i = this.channels[t];
      i && i.cueSplitAtTime(e);
    }
  }
}
function na(r, e, t) {
  t.a = r, t.b = e;
}
function MI(r, e, t) {
  return t.a === r && t.b === e;
}
function BI() {
  return {
    a: null,
    b: null
  };
}
var ah = function() {
  if (ao != null && ao.VTTCue)
    return self.VTTCue;
  const r = ["", "lr", "rl"], e = ["start", "middle", "end", "left", "right"];
  function t(o, c) {
    if (typeof c != "string" || !Array.isArray(o))
      return !1;
    const l = c.toLowerCase();
    return ~o.indexOf(l) ? l : !1;
  }
  function i(o) {
    return t(r, o);
  }
  function s(o) {
    return t(e, o);
  }
  function n(o, ...c) {
    let l = 1;
    for (; l < arguments.length; l++) {
      const d = arguments[l];
      for (const h in d)
        o[h] = d[h];
    }
    return o;
  }
  function a(o, c, l) {
    const d = this, h = {
      enumerable: !0
    };
    d.hasBeenReset = !1;
    let u = "", f = !1, p = o, m = c, g = l, x = null, _ = "", v = !0, E = "auto", b = "start", A = 50, C = "middle", I = 50, L = "middle";
    Object.defineProperty(d, "id", n({}, h, {
      get: function() {
        return u;
      },
      set: function(R) {
        u = "" + R;
      }
    })), Object.defineProperty(d, "pauseOnExit", n({}, h, {
      get: function() {
        return f;
      },
      set: function(R) {
        f = !!R;
      }
    })), Object.defineProperty(d, "startTime", n({}, h, {
      get: function() {
        return p;
      },
      set: function(R) {
        if (typeof R != "number")
          throw new TypeError("Start time must be set to a number.");
        p = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "endTime", n({}, h, {
      get: function() {
        return m;
      },
      set: function(R) {
        if (typeof R != "number")
          throw new TypeError("End time must be set to a number.");
        m = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "text", n({}, h, {
      get: function() {
        return g;
      },
      set: function(R) {
        g = "" + R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "region", n({}, h, {
      get: function() {
        return x;
      },
      set: function(R) {
        x = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "vertical", n({}, h, {
      get: function() {
        return _;
      },
      set: function(R) {
        const D = i(R);
        if (D === !1)
          throw new SyntaxError("An invalid or illegal string was specified.");
        _ = D, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "snapToLines", n({}, h, {
      get: function() {
        return v;
      },
      set: function(R) {
        v = !!R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "line", n({}, h, {
      get: function() {
        return E;
      },
      set: function(R) {
        if (typeof R != "number" && R !== "auto")
          throw new SyntaxError("An invalid number or illegal string was specified.");
        E = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "lineAlign", n({}, h, {
      get: function() {
        return b;
      },
      set: function(R) {
        const D = s(R);
        if (!D)
          throw new SyntaxError("An invalid or illegal string was specified.");
        b = D, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "position", n({}, h, {
      get: function() {
        return A;
      },
      set: function(R) {
        if (R < 0 || R > 100)
          throw new Error("Position must be between 0 and 100.");
        A = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "positionAlign", n({}, h, {
      get: function() {
        return C;
      },
      set: function(R) {
        const D = s(R);
        if (!D)
          throw new SyntaxError("An invalid or illegal string was specified.");
        C = D, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "size", n({}, h, {
      get: function() {
        return I;
      },
      set: function(R) {
        if (R < 0 || R > 100)
          throw new Error("Size must be between 0 and 100.");
        I = R, this.hasBeenReset = !0;
      }
    })), Object.defineProperty(d, "align", n({}, h, {
      get: function() {
        return L;
      },
      set: function(R) {
        const D = s(R);
        if (!D)
          throw new SyntaxError("An invalid or illegal string was specified.");
        L = D, this.hasBeenReset = !0;
      }
    })), d.displayState = void 0;
  }
  return a.prototype.getCueAsHTML = function() {
    return self.WebVTT.convertCueToDOMTree(self, this.text);
  }, a;
}();
class FI {
  decode(e, t) {
    if (!e)
      return "";
    if (typeof e != "string")
      throw new Error("Error - expected string data.");
    return decodeURIComponent(encodeURIComponent(e));
  }
}
function iy(r) {
  function e(i, s, n, a) {
    return (i | 0) * 3600 + (s | 0) * 60 + (n | 0) + parseFloat(a || 0);
  }
  const t = r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  return t ? parseFloat(t[2]) > 59 ? e(t[2], t[3], 0, t[4]) : e(t[1], t[2], t[3], t[4]) : null;
}
class OI {
  constructor() {
    this.values = /* @__PURE__ */ Object.create(null);
  }
  // Only accept the first assignment to any key.
  set(e, t) {
    !this.get(e) && t !== "" && (this.values[e] = t);
  }
  // Return the value for a key, or a default value.
  // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  // a number of possible default values as properties where 'defaultKey' is
  // the key of the property that will be chosen; otherwise it's assumed to be
  // a single value.
  get(e, t, i) {
    return i ? this.has(e) ? this.values[e] : t[i] : this.has(e) ? this.values[e] : t;
  }
  // Check whether we have a value for a key.
  has(e) {
    return e in this.values;
  }
  // Accept a setting if its one of the given alternatives.
  alt(e, t, i) {
    for (let s = 0; s < i.length; ++s)
      if (t === i[s]) {
        this.set(e, t);
        break;
      }
  }
  // Accept a setting if its a valid (signed) integer.
  integer(e, t) {
    /^-?\d+$/.test(t) && this.set(e, parseInt(t, 10));
  }
  // Accept a setting if its a valid percentage.
  percent(e, t) {
    if (/^([\d]{1,3})(\.[\d]*)?%$/.test(t)) {
      const i = parseFloat(t);
      if (i >= 0 && i <= 100)
        return this.set(e, i), !0;
    }
    return !1;
  }
}
function sy(r, e, t, i) {
  const s = i ? r.split(i) : [r];
  for (const n in s) {
    if (typeof s[n] != "string")
      continue;
    const a = s[n].split(t);
    if (a.length !== 2)
      continue;
    const o = a[0], c = a[1];
    e(o, c);
  }
}
const Zc = new ah(0, 0, ""), aa = Zc.align === "middle" ? "middle" : "center";
function NI(r, e, t) {
  const i = r;
  function s() {
    const o = iy(r);
    if (o === null)
      throw new Error("Malformed timestamp: " + i);
    return r = r.replace(/^[^\sa-zA-Z-]+/, ""), o;
  }
  function n(o, c) {
    const l = new OI();
    sy(o, function(u, f) {
      let p;
      switch (u) {
        case "region":
          for (let m = t.length - 1; m >= 0; m--)
            if (t[m].id === f) {
              l.set(u, t[m].region);
              break;
            }
          break;
        case "vertical":
          l.alt(u, f, ["rl", "lr"]);
          break;
        case "line":
          p = f.split(","), l.integer(u, p[0]), l.percent(u, p[0]) && l.set("snapToLines", !1), l.alt(u, p[0], ["auto"]), p.length === 2 && l.alt("lineAlign", p[1], ["start", aa, "end"]);
          break;
        case "position":
          p = f.split(","), l.percent(u, p[0]), p.length === 2 && l.alt("positionAlign", p[1], ["start", aa, "end", "line-left", "line-right", "auto"]);
          break;
        case "size":
          l.percent(u, f);
          break;
        case "align":
          l.alt(u, f, ["start", aa, "end", "left", "right"]);
          break;
      }
    }, /:/, /\s/), c.region = l.get("region", null), c.vertical = l.get("vertical", "");
    let d = l.get("line", "auto");
    d === "auto" && Zc.line === -1 && (d = -1), c.line = d, c.lineAlign = l.get("lineAlign", "start"), c.snapToLines = l.get("snapToLines", !0), c.size = l.get("size", 100), c.align = l.get("align", aa);
    let h = l.get("position", "auto");
    h === "auto" && Zc.position === 50 && (h = c.align === "start" || c.align === "left" ? 0 : c.align === "end" || c.align === "right" ? 100 : 50), c.position = h;
  }
  function a() {
    r = r.replace(/^\s+/, "");
  }
  if (a(), e.startTime = s(), a(), r.slice(0, 3) !== "-->")
    throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + i);
  r = r.slice(3), a(), e.endTime = s(), a(), n(r, e);
}
function ry(r) {
  return r.replace(/<br(?: \/)?>/gi, `
`);
}
class GI {
  constructor() {
    this.state = "INITIAL", this.buffer = "", this.decoder = new FI(), this.regionList = [], this.cue = null, this.oncue = void 0, this.onparsingerror = void 0, this.onflush = void 0;
  }
  parse(e) {
    const t = this;
    e && (t.buffer += t.decoder.decode(e, {
      stream: !0
    }));
    function i() {
      let n = t.buffer, a = 0;
      for (n = ry(n); a < n.length && n[a] !== "\r" && n[a] !== `
`; )
        ++a;
      const o = n.slice(0, a);
      return n[a] === "\r" && ++a, n[a] === `
` && ++a, t.buffer = n.slice(a), o;
    }
    function s(n) {
      sy(n, function(a, o) {
      }, /:/);
    }
    try {
      let n = "";
      if (t.state === "INITIAL") {
        if (!/\r\n|\n/.test(t.buffer))
          return this;
        n = i();
        const o = n.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);
        if (!(o != null && o[0]))
          throw new Error("Malformed WebVTT signature.");
        t.state = "HEADER";
      }
      let a = !1;
      for (; t.buffer; ) {
        if (!/\r\n|\n/.test(t.buffer))
          return this;
        switch (a ? a = !1 : n = i(), t.state) {
          case "HEADER":
            /:/.test(n) ? s(n) : n || (t.state = "ID");
            continue;
          case "NOTE":
            n || (t.state = "ID");
            continue;
          case "ID":
            if (/^NOTE($|[ \t])/.test(n)) {
              t.state = "NOTE";
              break;
            }
            if (!n)
              continue;
            if (t.cue = new ah(0, 0, ""), t.state = "CUE", n.indexOf("-->") === -1) {
              t.cue.id = n;
              continue;
            }
          case "CUE":
            if (!t.cue) {
              t.state = "BADCUE";
              continue;
            }
            try {
              NI(n, t.cue, t.regionList);
            } catch {
              t.cue = null, t.state = "BADCUE";
              continue;
            }
            t.state = "CUETEXT";
            continue;
          case "CUETEXT":
            {
              const o = n.indexOf("-->") !== -1;
              if (!n || o && (a = !0)) {
                t.oncue && t.cue && t.oncue(t.cue), t.cue = null, t.state = "ID";
                continue;
              }
              if (t.cue === null)
                continue;
              t.cue.text && (t.cue.text += `
`), t.cue.text += n;
            }
            continue;
          case "BADCUE":
            n || (t.state = "ID");
        }
      }
    } catch {
      t.state === "CUETEXT" && t.cue && t.oncue && t.oncue(t.cue), t.cue = null, t.state = t.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
    }
    return this;
  }
  flush() {
    const e = this;
    try {
      if ((e.cue || e.state === "HEADER") && (e.buffer += `

`, e.parse()), e.state === "INITIAL" || e.state === "BADWEBVTT")
        throw new Error("Malformed WebVTT signature.");
    } catch (t) {
      e.onparsingerror && e.onparsingerror(t);
    }
    return e.onflush && e.onflush(), this;
  }
}
const UI = /\r\n|\n\r|\n|\r/g, k0 = function(e, t, i = 0) {
  return e.slice(i, i + t.length) === t;
}, VI = function(e) {
  let t = parseInt(e.slice(-3));
  const i = parseInt(e.slice(-6, -4)), s = parseInt(e.slice(-9, -7)), n = e.length > 9 ? parseInt(e.substring(0, e.indexOf(":"))) : 0;
  if (!q(t) || !q(i) || !q(s) || !q(n))
    throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);
  return t += 1e3 * i, t += 60 * 1e3 * s, t += 60 * 60 * 1e3 * n, t;
};
function oh(r, e, t) {
  return dn(r.toString()) + dn(e.toString()) + dn(t);
}
const WI = function(e, t, i) {
  let s = e[t], n = e[s.prevCC];
  if (!n || !n.new && s.new) {
    e.ccOffset = e.presentationOffset = s.start, s.new = !1;
    return;
  }
  for (; (a = n) != null && a.new; ) {
    var a;
    e.ccOffset += s.start - n.start, s.new = !1, s = n, n = e[s.prevCC];
  }
  e.presentationOffset = i;
};
function HI(r, e, t, i, s, n, a) {
  const o = new GI(), c = $t(new Uint8Array(r)).trim().replace(UI, `
`).split(`
`), l = [], d = e ? j8(e.baseTime, e.timescale) : 0;
  let h = "00:00.000", u = 0, f = 0, p, m = !0;
  o.oncue = function(g) {
    const x = t[i];
    let _ = t.ccOffset;
    const v = (u - d) / 9e4;
    if (x != null && x.new && (f !== void 0 ? _ = t.ccOffset = x.start : WI(t, i, v)), v) {
      if (!e) {
        p = new Error("Missing initPTS for VTT MPEGTS");
        return;
      }
      _ = v - t.presentationOffset;
    }
    const E = g.endTime - g.startTime, b = Yt((g.startTime + _ - f) * 9e4, s * 9e4) / 9e4;
    g.startTime = Math.max(b, 0), g.endTime = Math.max(b + E, 0);
    const A = g.text.trim();
    g.text = decodeURIComponent(encodeURIComponent(A)), g.id || (g.id = oh(g.startTime, g.endTime, A)), g.endTime > 0 && l.push(g);
  }, o.onparsingerror = function(g) {
    p = g;
  }, o.onflush = function() {
    if (p) {
      a(p);
      return;
    }
    n(l);
  }, c.forEach((g) => {
    if (m)
      if (k0(g, "X-TIMESTAMP-MAP=")) {
        m = !1, g.slice(16).split(",").forEach((x) => {
          k0(x, "LOCAL:") ? h = x.slice(6) : k0(x, "MPEGTS:") && (u = parseInt(x.slice(7)));
        });
        try {
          f = VI(h) / 1e3;
        } catch (x) {
          p = x;
        }
        return;
      } else g === "" && (m = !1);
    o.parse(g + `
`);
  }), o.flush();
}
const w0 = "stpp.ttml.im1t", ny = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/, ay = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/, ZI = {
  left: "start",
  center: "center",
  right: "end",
  start: "start",
  end: "end"
};
function jp(r, e, t, i) {
  const s = pe(new Uint8Array(r), ["mdat"]);
  if (s.length === 0) {
    i(new Error("Could not parse IMSC1 mdat"));
    return;
  }
  const n = s.map((o) => $t(o)), a = z8(e.baseTime, 1, e.timescale);
  try {
    n.forEach((o) => t($I(o, a)));
  } catch (o) {
    i(o);
  }
}
function $I(r, e) {
  const s = new DOMParser().parseFromString(r, "text/xml").getElementsByTagName("tt")[0];
  if (!s)
    throw new Error("Invalid ttml");
  const n = {
    frameRate: 30,
    subFrameRate: 1,
    frameRateMultiplier: 0,
    tickRate: 0
  }, a = Object.keys(n).reduce((h, u) => (h[u] = s.getAttribute(`ttp:${u}`) || n[u], h), {}), o = s.getAttribute("xml:space") !== "preserve", c = Qp(M0(s, "styling", "style")), l = Qp(M0(s, "layout", "region")), d = M0(s, "body", "[begin]");
  return [].map.call(d, (h) => {
    const u = oy(h, o);
    if (!u || !h.hasAttribute("begin"))
      return null;
    const f = F0(h.getAttribute("begin"), a), p = F0(h.getAttribute("dur"), a);
    let m = F0(h.getAttribute("end"), a);
    if (f === null)
      throw Jp(h);
    if (m === null) {
      if (p === null)
        throw Jp(h);
      m = f + p;
    }
    const g = new ah(f - e, m - e, u);
    g.id = oh(g.startTime, g.endTime, g.text);
    const x = l[h.getAttribute("region")], _ = c[h.getAttribute("style")], v = KI(x, _, c), {
      textAlign: E
    } = v;
    if (E) {
      const b = ZI[E];
      b && (g.lineAlign = b), g.align = E;
    }
    return Me(g, v), g;
  }).filter((h) => h !== null);
}
function M0(r, e, t) {
  const i = r.getElementsByTagName(e)[0];
  return i ? [].slice.call(i.querySelectorAll(t)) : [];
}
function Qp(r) {
  return r.reduce((e, t) => {
    const i = t.getAttribute("xml:id");
    return i && (e[i] = t), e;
  }, {});
}
function oy(r, e) {
  return [].slice.call(r.childNodes).reduce((t, i, s) => {
    var n;
    return i.nodeName === "br" && s ? t + `
` : (n = i.childNodes) != null && n.length ? oy(i, e) : e ? t + i.textContent.trim().replace(/\s+/g, " ") : t + i.textContent;
  }, "");
}
function KI(r, e, t) {
  const i = "http://www.w3.org/ns/ttml#styling";
  let s = null;
  const n = [
    "displayAlign",
    "textAlign",
    "color",
    "backgroundColor",
    "fontSize",
    "fontFamily"
    // 'fontWeight',
    // 'lineHeight',
    // 'wrapOption',
    // 'fontStyle',
    // 'direction',
    // 'writingMode'
  ], a = r != null && r.hasAttribute("style") ? r.getAttribute("style") : null;
  return a && t.hasOwnProperty(a) && (s = t[a]), n.reduce((o, c) => {
    const l = B0(e, i, c) || B0(r, i, c) || B0(s, i, c);
    return l && (o[c] = l), o;
  }, {});
}
function B0(r, e, t) {
  return r && r.hasAttributeNS(e, t) ? r.getAttributeNS(e, t) : null;
}
function Jp(r) {
  return new Error(`Could not parse ttml timestamp ${r}`);
}
function F0(r, e) {
  if (!r)
    return null;
  let t = iy(r);
  return t === null && (ny.test(r) ? t = XI(r, e) : ay.test(r) && (t = YI(r, e))), t;
}
function XI(r, e) {
  const t = ny.exec(r), i = (t[4] | 0) + (t[5] | 0) / e.subFrameRate;
  return (t[1] | 0) * 3600 + (t[2] | 0) * 60 + (t[3] | 0) + i / e.frameRate;
}
function YI(r, e) {
  const t = ay.exec(r), i = Number(t[1]);
  switch (t[2]) {
    case "h":
      return i * 3600;
    case "m":
      return i * 60;
    case "ms":
      return i * 1e3;
    case "f":
      return i / e.frameRate;
    case "t":
      return i / e.tickRate;
  }
  return i;
}
class oa {
  constructor(e, t) {
    this.timelineController = void 0, this.cueRanges = [], this.trackName = void 0, this.startTime = null, this.endTime = null, this.screen = null, this.timelineController = e, this.trackName = t;
  }
  dispatchCue() {
    this.startTime !== null && (this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges), this.startTime = null);
  }
  newCue(e, t, i) {
    (this.startTime === null || this.startTime > e) && (this.startTime = e), this.endTime = t, this.screen = i, this.timelineController.createCaptionsTrack(this.trackName);
  }
  reset() {
    this.cueRanges = [], this.startTime = null;
  }
}
class zI {
  constructor(e) {
    this.hls = void 0, this.media = null, this.config = void 0, this.enabled = !0, this.Cues = void 0, this.textTracks = [], this.tracks = [], this.initPTS = [], this.unparsedVttFrags = [], this.captionsTracks = {}, this.nonNativeCaptionsTracks = {}, this.cea608Parser1 = void 0, this.cea608Parser2 = void 0, this.lastCc = -1, this.lastSn = -1, this.lastPartIndex = -1, this.prevCC = -1, this.vttCCs = em(), this.captionsProperties = void 0, this.hls = e, this.config = e.config, this.Cues = e.config.cueHandler, this.captionsProperties = {
      textTrack1: {
        label: this.config.captionsTextTrack1Label,
        languageCode: this.config.captionsTextTrack1LanguageCode
      },
      textTrack2: {
        label: this.config.captionsTextTrack2Label,
        languageCode: this.config.captionsTextTrack2LanguageCode
      },
      textTrack3: {
        label: this.config.captionsTextTrack3Label,
        languageCode: this.config.captionsTextTrack3LanguageCode
      },
      textTrack4: {
        label: this.config.captionsTextTrack4Label,
        languageCode: this.config.captionsTextTrack4LanguageCode
      }
    }, e.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.on(T.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this), e.on(T.FRAG_LOADING, this.onFragLoading, this), e.on(T.FRAG_LOADED, this.onFragLoaded, this), e.on(T.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this), e.on(T.FRAG_DECRYPTED, this.onFragDecrypted, this), e.on(T.INIT_PTS_FOUND, this.onInitPtsFound, this), e.on(T.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this), e.on(T.BUFFER_FLUSHING, this.onBufferFlushing, this);
  }
  destroy() {
    const {
      hls: e
    } = this;
    e.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.off(T.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this), e.off(T.FRAG_LOADING, this.onFragLoading, this), e.off(T.FRAG_LOADED, this.onFragLoaded, this), e.off(T.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this), e.off(T.FRAG_DECRYPTED, this.onFragDecrypted, this), e.off(T.INIT_PTS_FOUND, this.onInitPtsFound, this), e.off(T.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this), e.off(T.BUFFER_FLUSHING, this.onBufferFlushing, this), this.hls = this.config = this.media = null, this.cea608Parser1 = this.cea608Parser2 = void 0;
  }
  initCea608Parsers() {
    const e = new oa(this, "textTrack1"), t = new oa(this, "textTrack2"), i = new oa(this, "textTrack3"), s = new oa(this, "textTrack4");
    this.cea608Parser1 = new zp(1, e, t), this.cea608Parser2 = new zp(3, i, s);
  }
  addCues(e, t, i, s, n) {
    let a = !1;
    for (let o = n.length; o--; ) {
      const c = n[o], l = jI(c[0], c[1], t, i);
      if (l >= 0 && (c[0] = Math.min(c[0], t), c[1] = Math.max(c[1], i), a = !0, l / (i - t) > 0.5))
        return;
    }
    if (a || n.push([t, i]), this.config.renderTextTracksNatively) {
      const o = this.captionsTracks[e];
      this.Cues.newCue(o, t, i, s);
    } else {
      const o = this.Cues.newCue(null, t, i, s);
      this.hls.trigger(T.CUES_PARSED, {
        type: "captions",
        cues: o,
        track: e
      });
    }
  }
  // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  onInitPtsFound(e, {
    frag: t,
    id: i,
    initPTS: s,
    timescale: n,
    trackId: a
  }) {
    const {
      unparsedVttFrags: o
    } = this;
    i === te.MAIN && (this.initPTS[t.cc] = {
      baseTime: s,
      timescale: n,
      trackId: a
    }), o.length && (this.unparsedVttFrags = [], o.forEach((c) => {
      this.initPTS[c.frag.cc] ? this.onFragLoaded(T.FRAG_LOADED, c) : this.hls.trigger(T.SUBTITLE_FRAG_PROCESSED, {
        success: !1,
        frag: c.frag,
        error: new Error("Subtitle discontinuity domain does not match main")
      });
    }));
  }
  getExistingTrack(e, t) {
    const {
      media: i
    } = this;
    if (i)
      for (let s = 0; s < i.textTracks.length; s++) {
        const n = i.textTracks[s];
        if (qp(n, {
          name: e,
          lang: t,
          characteristics: "transcribes-spoken-dialog,describes-music-and-sound"
        }))
          return n;
      }
    return null;
  }
  createCaptionsTrack(e) {
    this.config.renderTextTracksNatively ? this.createNativeTrack(e) : this.createNonNativeTrack(e);
  }
  createNativeTrack(e) {
    if (this.captionsTracks[e])
      return;
    const {
      captionsProperties: t,
      captionsTracks: i,
      media: s
    } = this, {
      label: n,
      languageCode: a
    } = t[e], o = this.getExistingTrack(n, a);
    if (o)
      i[e] = o, mr(i[e]), Q_(i[e], s);
    else {
      const c = this.createTextTrack("captions", n, a);
      c && (c[e] = !0, i[e] = c);
    }
  }
  createNonNativeTrack(e) {
    if (this.nonNativeCaptionsTracks[e])
      return;
    const t = this.captionsProperties[e];
    if (!t)
      return;
    const i = t.label, s = {
      _id: e,
      label: i,
      kind: "captions",
      default: t.media ? !!t.media.default : !1,
      closedCaptions: t.media
    };
    this.nonNativeCaptionsTracks[e] = s, this.hls.trigger(T.NON_NATIVE_TEXT_TRACKS_FOUND, {
      tracks: [s]
    });
  }
  createTextTrack(e, t, i) {
    const s = this.media;
    if (s)
      return s.addTextTrack(e, t, i);
  }
  onMediaAttaching(e, t) {
    this.media = t.media, t.mediaSource || this._cleanTracks();
  }
  onMediaDetaching(e, t) {
    const i = !!t.transferMedia;
    if (this.media = null, i)
      return;
    const {
      captionsTracks: s
    } = this;
    Object.keys(s).forEach((n) => {
      mr(s[n]), delete s[n];
    }), this.nonNativeCaptionsTracks = {};
  }
  onManifestLoading() {
    this.lastCc = -1, this.lastSn = -1, this.lastPartIndex = -1, this.prevCC = -1, this.vttCCs = em(), this._cleanTracks(), this.tracks = [], this.captionsTracks = {}, this.nonNativeCaptionsTracks = {}, this.textTracks = [], this.unparsedVttFrags = [], this.initPTS = [], this.cea608Parser1 && this.cea608Parser2 && (this.cea608Parser1.reset(), this.cea608Parser2.reset());
  }
  _cleanTracks() {
    const {
      media: e
    } = this;
    if (!e)
      return;
    const t = e.textTracks;
    if (t)
      for (let i = 0; i < t.length; i++)
        mr(t[i]);
  }
  onSubtitleTracksUpdated(e, t) {
    const i = t.subtitleTracks || [], s = i.some((n) => n.textCodec === w0);
    if (this.config.enableWebVTT || s && this.config.enableIMSC1) {
      if (N_(this.tracks, i)) {
        this.tracks = i;
        return;
      }
      if (this.textTracks = [], this.tracks = i, this.config.renderTextTracksNatively) {
        const a = this.media, o = a ? Ba(a.textTracks) : null;
        if (this.tracks.forEach((c, l) => {
          let d;
          if (o) {
            let h = null;
            for (let u = 0; u < o.length; u++)
              if (o[u] && qp(o[u], c)) {
                h = o[u], o[u] = null;
                break;
              }
            h && (d = h);
          }
          if (d)
            mr(d);
          else {
            const h = ly(c);
            d = this.createTextTrack(h, c.name, c.lang), d && (d.mode = "disabled");
          }
          d && this.textTracks.push(d);
        }), o != null && o.length) {
          const c = o.filter((l) => l !== null).map((l) => l.label);
          c.length && this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);
        }
      } else if (this.tracks.length) {
        const a = this.tracks.map((o) => ({
          label: o.name,
          kind: o.type.toLowerCase(),
          default: o.default,
          subtitleTrack: o
        }));
        this.hls.trigger(T.NON_NATIVE_TEXT_TRACKS_FOUND, {
          tracks: a
        });
      }
    }
  }
  onManifestLoaded(e, t) {
    this.config.enableCEA708Captions && t.captions && t.captions.forEach((i) => {
      const s = /(?:CC|SERVICE)([1-4])/.exec(i.instreamId);
      if (!s)
        return;
      const n = `textTrack${s[1]}`, a = this.captionsProperties[n];
      a && (a.label = i.name, i.lang && (a.languageCode = i.lang), a.media = i);
    });
  }
  closedCaptionsForLevel(e) {
    const t = this.hls.levels[e.level];
    return t == null ? void 0 : t.attrs["CLOSED-CAPTIONS"];
  }
  onFragLoading(e, t) {
    if (this.enabled && t.frag.type === te.MAIN) {
      var i, s;
      const {
        cea608Parser1: n,
        cea608Parser2: a,
        lastSn: o
      } = this, {
        cc: c,
        sn: l
      } = t.frag, d = (i = (s = t.part) == null ? void 0 : s.index) != null ? i : -1;
      n && a && (l !== o + 1 || l === o && d !== this.lastPartIndex + 1 || c !== this.lastCc) && (n.reset(), a.reset()), this.lastCc = c, this.lastSn = l, this.lastPartIndex = d;
    }
  }
  onFragLoaded(e, t) {
    const {
      frag: i,
      payload: s
    } = t;
    if (i.type === te.SUBTITLE)
      if (s.byteLength) {
        const n = i.decryptdata, a = "stats" in t;
        if (n == null || !n.encrypted || a) {
          const o = this.tracks[i.level], c = this.vttCCs;
          c[i.cc] || (c[i.cc] = {
            start: i.start,
            prevCC: this.prevCC,
            new: !0
          }, this.prevCC = i.cc), o && o.textCodec === w0 ? this._parseIMSC1(i, s) : this._parseVTTs(t);
        }
      } else
        this.hls.trigger(T.SUBTITLE_FRAG_PROCESSED, {
          success: !1,
          frag: i,
          error: new Error("Empty subtitle payload")
        });
  }
  _parseIMSC1(e, t) {
    const i = this.hls;
    jp(t, this.initPTS[e.cc], (s) => {
      this._appendCues(s, e.level), i.trigger(T.SUBTITLE_FRAG_PROCESSED, {
        success: !0,
        frag: e
      });
    }, (s) => {
      i.logger.log(`Failed to parse IMSC1: ${s}`), i.trigger(T.SUBTITLE_FRAG_PROCESSED, {
        success: !1,
        frag: e,
        error: s
      });
    });
  }
  _parseVTTs(e) {
    var t;
    const {
      frag: i,
      payload: s
    } = e, {
      initPTS: n,
      unparsedVttFrags: a
    } = this, o = n.length - 1;
    if (!n[i.cc] && o === -1) {
      a.push(e);
      return;
    }
    const c = this.hls, l = (t = i.initSegment) != null && t.data ? Qt(i.initSegment.data, new Uint8Array(s)).buffer : s;
    HI(l, this.initPTS[i.cc], this.vttCCs, i.cc, i.start, (d) => {
      this._appendCues(d, i.level), c.trigger(T.SUBTITLE_FRAG_PROCESSED, {
        success: !0,
        frag: i
      });
    }, (d) => {
      const h = d.message === "Missing initPTS for VTT MPEGTS";
      h ? a.push(e) : this._fallbackToIMSC1(i, s), c.logger.log(`Failed to parse VTT cue: ${d}`), !(h && o > i.cc) && c.trigger(T.SUBTITLE_FRAG_PROCESSED, {
        success: !1,
        frag: i,
        error: d
      });
    });
  }
  _fallbackToIMSC1(e, t) {
    const i = this.tracks[e.level];
    i.textCodec || jp(t, this.initPTS[e.cc], () => {
      i.textCodec = w0, this._parseIMSC1(e, t);
    }, () => {
      i.textCodec = "wvtt";
    });
  }
  _appendCues(e, t) {
    const i = this.hls;
    if (this.config.renderTextTracksNatively) {
      const s = this.textTracks[t];
      if (!s || s.mode === "disabled")
        return;
      e.forEach((n) => J_(s, n));
    } else {
      const s = this.tracks[t];
      if (!s)
        return;
      const n = s.default ? "default" : "subtitles" + t;
      i.trigger(T.CUES_PARSED, {
        type: "subtitles",
        cues: e,
        track: n
      });
    }
  }
  onFragDecrypted(e, t) {
    const {
      frag: i
    } = t;
    i.type === te.SUBTITLE && this.onFragLoaded(T.FRAG_LOADED, t);
  }
  onSubtitleTracksCleared() {
    this.tracks = [], this.captionsTracks = {};
  }
  onFragParsingUserdata(e, t) {
    if (!this.enabled || !this.config.enableCEA708Captions)
      return;
    const {
      frag: i,
      samples: s
    } = t;
    if (!(i.type === te.MAIN && this.closedCaptionsForLevel(i) === "NONE"))
      for (let n = 0; n < s.length; n++) {
        const a = s[n].bytes;
        if (a) {
          this.cea608Parser1 || this.initCea608Parsers();
          const o = this.extractCea608Data(a);
          this.cea608Parser1.addData(s[n].pts, o[0]), this.cea608Parser2.addData(s[n].pts, o[1]);
        }
      }
  }
  onBufferFlushing(e, {
    startOffset: t,
    endOffset: i,
    endOffsetSubtitles: s,
    type: n
  }) {
    const {
      media: a
    } = this;
    if (!(!a || a.currentTime < i)) {
      if (!n || n === "video") {
        const {
          captionsTracks: o
        } = this;
        Object.keys(o).forEach((c) => Hc(o[c], t, i));
      }
      if (this.config.renderTextTracksNatively && t === 0 && s !== void 0) {
        const {
          textTracks: o
        } = this;
        Object.keys(o).forEach((c) => Hc(o[c], t, s));
      }
    }
  }
  extractCea608Data(e) {
    const t = [[], []], i = e[0] & 31;
    let s = 2;
    for (let n = 0; n < i; n++) {
      const a = e[s++], o = 127 & e[s++], c = 127 & e[s++];
      if (o === 0 && c === 0)
        continue;
      if ((4 & a) !== 0) {
        const d = 3 & a;
        (d === 0 || d === 1) && (t[d].push(o), t[d].push(c));
      }
    }
    return t;
  }
}
function ly(r) {
  return r.characteristics && /transcribes-spoken-dialog/gi.test(r.characteristics) && /describes-music-and-sound/gi.test(r.characteristics) ? "captions" : "subtitles";
}
function qp(r, e) {
  return !!r && r.kind === ly(e) && Gc(e, r);
}
function jI(r, e, t, i) {
  return Math.min(e, i) - Math.max(r, t);
}
function em() {
  return {
    ccOffset: 0,
    presentationOffset: 0,
    0: {
      start: 0,
      prevCC: -1,
      new: !0
    }
  };
}
const QI = /\s/, JI = {
  newCue(r, e, t, i) {
    const s = [];
    let n, a, o, c, l;
    const d = self.VTTCue || self.TextTrackCue;
    for (let u = 0; u < i.rows.length; u++)
      if (n = i.rows[u], o = !0, c = 0, l = "", !n.isEmpty()) {
        var h;
        for (let m = 0; m < n.chars.length; m++)
          QI.test(n.chars[m].uchar) && o ? c++ : (l += n.chars[m].uchar, o = !1);
        n.cueStartTime = e, e === t && (t += 1e-4), c >= 16 ? c-- : c++;
        const f = ry(l.trim()), p = oh(e, t, f);
        r != null && (h = r.cues) != null && h.getCueById(p) || (a = new d(e, t, f), a.id = p, a.line = u + 1, a.align = "left", a.position = 10 + Math.min(80, Math.floor(c * 8 / 32) * 10), s.push(a));
      }
    return r && s.length && (s.sort((u, f) => u.line === "auto" || f.line === "auto" ? 0 : u.line > 8 && f.line > 8 ? f.line - u.line : u.line - f.line), s.forEach((u) => J_(r, u))), s;
  }
};
function qI() {
  if (
    // @ts-ignore
    self.fetch && self.AbortController && self.ReadableStream && self.Request
  )
    try {
      return new self.ReadableStream({}), !0;
    } catch {
    }
  return !1;
}
const e5 = /(\d+)-(\d+)\/(\d+)/;
class tm {
  constructor(e) {
    this.fetchSetup = void 0, this.requestTimeout = void 0, this.request = null, this.response = null, this.controller = void 0, this.context = null, this.config = null, this.callbacks = null, this.stats = void 0, this.loader = null, this.fetchSetup = e.fetchSetup || r5, this.controller = new self.AbortController(), this.stats = new Gd();
  }
  destroy() {
    this.loader = this.callbacks = this.context = this.config = this.request = null, this.abortInternal(), this.response = null, this.fetchSetup = this.controller = this.stats = null;
  }
  abortInternal() {
    this.controller && !this.stats.loading.end && (this.stats.aborted = !0, this.controller.abort());
  }
  abort() {
    var e;
    this.abortInternal(), (e = this.callbacks) != null && e.onAbort && this.callbacks.onAbort(this.stats, this.context, this.response);
  }
  load(e, t, i) {
    const s = this.stats;
    if (s.loading.start)
      throw new Error("Loader can only be used once.");
    s.loading.start = self.performance.now();
    const n = t5(e, this.controller.signal), a = e.responseType === "arraybuffer", o = a ? "byteLength" : "length", {
      maxTimeToFirstByteMs: c,
      maxLoadTimeMs: l
    } = t.loadPolicy;
    this.context = e, this.config = t, this.callbacks = i, this.request = this.fetchSetup(e, n), self.clearTimeout(this.requestTimeout), t.timeout = c && q(c) ? c : l, this.requestTimeout = self.setTimeout(() => {
      this.callbacks && (this.abortInternal(), this.callbacks.onTimeout(s, e, this.response));
    }, t.timeout), (bn(this.request) ? this.request.then(self.fetch) : self.fetch(this.request)).then((h) => {
      var u;
      this.response = this.loader = h;
      const f = Math.max(self.performance.now(), s.loading.start);
      if (self.clearTimeout(this.requestTimeout), t.timeout = l, this.requestTimeout = self.setTimeout(() => {
        this.callbacks && (this.abortInternal(), this.callbacks.onTimeout(s, e, this.response));
      }, l - (f - s.loading.start)), !h.ok) {
        const {
          status: m,
          statusText: g
        } = h;
        throw new n5(g || "fetch, bad network response", m, h);
      }
      s.loading.first = f, s.total = s5(h.headers) || s.total;
      const p = (u = this.callbacks) == null ? void 0 : u.onProgress;
      return p && q(t.highWaterMark) ? this.loadProgressively(h, s, e, t.highWaterMark, p) : a ? h.arrayBuffer() : e.responseType === "json" ? h.json() : h.text();
    }).then((h) => {
      var u, f;
      const p = this.response;
      if (!p)
        throw new Error("loader destroyed");
      self.clearTimeout(this.requestTimeout), s.loading.end = Math.max(self.performance.now(), s.loading.first);
      const m = h[o];
      m && (s.loaded = s.total = m);
      const g = {
        url: p.url,
        data: h,
        code: p.status
      }, x = (u = this.callbacks) == null ? void 0 : u.onProgress;
      x && !q(t.highWaterMark) && x(s, e, h, p), (f = this.callbacks) == null || f.onSuccess(g, s, e, p);
    }).catch((h) => {
      var u;
      if (self.clearTimeout(this.requestTimeout), s.aborted)
        return;
      const f = h && h.code || 0, p = h ? h.message : null;
      (u = this.callbacks) == null || u.onError({
        code: f,
        text: p
      }, e, h ? h.details : null, s);
    });
  }
  getCacheAge() {
    let e = null;
    if (this.response) {
      const t = this.response.headers.get("age");
      e = t ? parseFloat(t) : null;
    }
    return e;
  }
  getResponseHeader(e) {
    return this.response ? this.response.headers.get(e) : null;
  }
  loadProgressively(e, t, i, s = 0, n) {
    const a = new y_(), o = e.body.getReader(), c = () => o.read().then((l) => {
      if (l.done)
        return a.dataLength && n(t, i, a.flush().buffer, e), Promise.resolve(new ArrayBuffer(0));
      const d = l.value, h = d.length;
      return t.loaded += h, h < s || a.dataLength ? (a.push(d), a.dataLength >= s && n(t, i, a.flush().buffer, e)) : n(t, i, d.buffer, e), c();
    }).catch(() => Promise.reject());
    return c();
  }
}
function t5(r, e) {
  const t = {
    method: "GET",
    mode: "cors",
    credentials: "same-origin",
    signal: e,
    headers: new self.Headers(Me({}, r.headers))
  };
  return r.rangeEnd && t.headers.set("Range", "bytes=" + r.rangeStart + "-" + String(r.rangeEnd - 1)), t;
}
function i5(r) {
  const e = e5.exec(r);
  if (e)
    return parseInt(e[2]) - parseInt(e[1]) + 1;
}
function s5(r) {
  const e = r.get("Content-Range");
  if (e) {
    const i = i5(e);
    if (q(i))
      return i;
  }
  const t = r.get("Content-Length");
  if (t)
    return parseInt(t);
}
function r5(r, e) {
  return new self.Request(r.url, e);
}
class n5 extends Error {
  constructor(e, t, i) {
    super(e), this.code = void 0, this.details = void 0, this.code = t, this.details = i;
  }
}
const a5 = /^age:\s*[\d.]+\s*$/im;
class cy {
  constructor(e) {
    this.xhrSetup = void 0, this.requestTimeout = void 0, this.retryTimeout = void 0, this.retryDelay = void 0, this.config = null, this.callbacks = null, this.context = null, this.loader = null, this.stats = void 0, this.xhrSetup = e && e.xhrSetup || null, this.stats = new Gd(), this.retryDelay = 0;
  }
  destroy() {
    this.callbacks = null, this.abortInternal(), this.loader = null, this.config = null, this.context = null, this.xhrSetup = null;
  }
  abortInternal() {
    const e = this.loader;
    self.clearTimeout(this.requestTimeout), self.clearTimeout(this.retryTimeout), e && (e.onreadystatechange = null, e.onprogress = null, e.readyState !== 4 && (this.stats.aborted = !0, e.abort()));
  }
  abort() {
    var e;
    this.abortInternal(), (e = this.callbacks) != null && e.onAbort && this.callbacks.onAbort(this.stats, this.context, this.loader);
  }
  load(e, t, i) {
    if (this.stats.loading.start)
      throw new Error("Loader can only be used once.");
    this.stats.loading.start = self.performance.now(), this.context = e, this.config = t, this.callbacks = i, this.loadInternal();
  }
  loadInternal() {
    const {
      config: e,
      context: t
    } = this;
    if (!e || !t)
      return;
    const i = this.loader = new self.XMLHttpRequest(), s = this.stats;
    s.loading.first = 0, s.loaded = 0, s.aborted = !1;
    const n = this.xhrSetup;
    n ? Promise.resolve().then(() => {
      if (!(this.loader !== i || this.stats.aborted))
        return n(i, t.url);
    }).catch((a) => {
      if (!(this.loader !== i || this.stats.aborted))
        return i.open("GET", t.url, !0), n(i, t.url);
    }).then(() => {
      this.loader !== i || this.stats.aborted || this.openAndSendXhr(i, t, e);
    }).catch((a) => {
      var o;
      (o = this.callbacks) == null || o.onError({
        code: i.status,
        text: a.message
      }, t, i, s);
    }) : this.openAndSendXhr(i, t, e);
  }
  openAndSendXhr(e, t, i) {
    e.readyState || e.open("GET", t.url, !0);
    const s = t.headers, {
      maxTimeToFirstByteMs: n,
      maxLoadTimeMs: a
    } = i.loadPolicy;
    if (s)
      for (const o in s)
        e.setRequestHeader(o, s[o]);
    t.rangeEnd && e.setRequestHeader("Range", "bytes=" + t.rangeStart + "-" + (t.rangeEnd - 1)), e.onreadystatechange = this.readystatechange.bind(this), e.onprogress = this.loadprogress.bind(this), e.responseType = t.responseType, self.clearTimeout(this.requestTimeout), i.timeout = n && q(n) ? n : a, this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), i.timeout), e.send();
  }
  readystatechange() {
    const {
      context: e,
      loader: t,
      stats: i
    } = this;
    if (!e || !t)
      return;
    const s = t.readyState, n = this.config;
    if (!i.aborted && s >= 2 && (i.loading.first === 0 && (i.loading.first = Math.max(self.performance.now(), i.loading.start), n.timeout !== n.loadPolicy.maxLoadTimeMs && (self.clearTimeout(this.requestTimeout), n.timeout = n.loadPolicy.maxLoadTimeMs, this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), n.loadPolicy.maxLoadTimeMs - (i.loading.first - i.loading.start)))), s === 4)) {
      self.clearTimeout(this.requestTimeout), t.onreadystatechange = null, t.onprogress = null;
      const l = t.status, d = t.responseType === "text" ? t.responseText : null;
      if (l >= 200 && l < 300) {
        const p = d ?? t.response;
        if (p != null) {
          var a, o;
          i.loading.end = Math.max(self.performance.now(), i.loading.first);
          const m = t.responseType === "arraybuffer" ? p.byteLength : p.length;
          i.loaded = i.total = m, i.bwEstimate = i.total * 8e3 / (i.loading.end - i.loading.first);
          const g = (a = this.callbacks) == null ? void 0 : a.onProgress;
          g && g(i, e, p, t);
          const x = {
            url: t.responseURL,
            data: p,
            code: l
          };
          (o = this.callbacks) == null || o.onSuccess(x, i, e, t);
          return;
        }
      }
      const h = n.loadPolicy.errorRetry, u = i.retry, f = {
        url: e.url,
        data: void 0,
        code: l
      };
      if (no(h, u, !1, f))
        this.retry(h);
      else {
        var c;
        Pe.error(`${l} while loading ${e.url}`), (c = this.callbacks) == null || c.onError({
          code: l,
          text: t.statusText
        }, e, t, i);
      }
    }
  }
  loadtimeout() {
    if (!this.config) return;
    const e = this.config.loadPolicy.timeoutRetry, t = this.stats.retry;
    if (no(e, t, !0))
      this.retry(e);
    else {
      var i;
      Pe.warn(`timeout while loading ${(i = this.context) == null ? void 0 : i.url}`);
      const s = this.callbacks;
      s && (this.abortInternal(), s.onTimeout(this.stats, this.context, this.loader));
    }
  }
  retry(e) {
    const {
      context: t,
      stats: i
    } = this;
    this.retryDelay = Hd(e, i.retry), i.retry++, Pe.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${t == null ? void 0 : t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`), this.abortInternal(), this.loader = null, self.clearTimeout(this.retryTimeout), this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  }
  loadprogress(e) {
    const t = this.stats;
    t.loaded = e.loaded, e.lengthComputable && (t.total = e.total);
  }
  getCacheAge() {
    let e = null;
    if (this.loader && a5.test(this.loader.getAllResponseHeaders())) {
      const t = this.loader.getResponseHeader("age");
      e = t ? parseFloat(t) : null;
    }
    return e;
  }
  getResponseHeader(e) {
    return this.loader && new RegExp(`^${e}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders()) ? this.loader.getResponseHeader(e) : null;
  }
}
const o5 = {
  maxTimeToFirstByteMs: 8e3,
  maxLoadTimeMs: 2e4,
  timeoutRetry: null,
  errorRetry: null
}, l5 = we(we({
  autoStartLoad: !0,
  // used by stream-controller
  startPosition: -1,
  // used by stream-controller
  defaultAudioCodec: void 0,
  // used by stream-controller
  debug: !1,
  // used by logger
  capLevelOnFPSDrop: !1,
  // used by fps-controller
  capLevelToPlayerSize: !1,
  // used by cap-level-controller
  ignoreDevicePixelRatio: !1,
  // used by cap-level-controller
  maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  // used by cap-level-controller
  preferManagedMediaSource: !0,
  initialLiveManifestSize: 1,
  // used by stream-controller
  maxBufferLength: 30,
  // used by stream-controller
  backBufferLength: 1 / 0,
  // used by buffer-controller
  frontBufferFlushThreshold: 1 / 0,
  startOnSegmentBoundary: !1,
  // used by stream-controller
  maxBufferSize: 60 * 1e3 * 1e3,
  // used by stream-controller
  maxFragLookUpTolerance: 0.25,
  // used by stream-controller
  maxBufferHole: 0.1,
  // used by stream-controller and gap-controller
  detectStallWithCurrentTimeMs: 1250,
  // used by gap-controller
  highBufferWatchdogPeriod: 2,
  // used by gap-controller
  nudgeOffset: 0.1,
  // used by gap-controller
  nudgeMaxRetry: 3,
  // used by gap-controller
  nudgeOnVideoHole: !0,
  // used by gap-controller
  liveSyncMode: "edge",
  // used by stream-controller
  liveSyncDurationCount: 3,
  // used by latency-controller
  liveSyncOnStallIncrease: 1,
  // used by latency-controller
  liveMaxLatencyDurationCount: 1 / 0,
  // used by latency-controller
  liveSyncDuration: void 0,
  // used by latency-controller
  liveMaxLatencyDuration: void 0,
  // used by latency-controller
  maxLiveSyncPlaybackRate: 1,
  // used by latency-controller
  liveDurationInfinity: !1,
  // used by buffer-controller
  /**
   * @deprecated use backBufferLength
   */
  liveBackBufferLength: null,
  // used by buffer-controller
  maxMaxBufferLength: 600,
  // used by stream-controller
  enableWorker: !0,
  // used by transmuxer
  workerPath: null,
  // used by transmuxer
  enableSoftwareAES: !0,
  // used by decrypter
  startLevel: void 0,
  // used by level-controller
  startFragPrefetch: !1,
  // used by stream-controller
  fpsDroppedMonitoringPeriod: 5e3,
  // used by fps-controller
  fpsDroppedMonitoringThreshold: 0.2,
  // used by fps-controller
  appendErrorMaxRetry: 3,
  // used by buffer-controller
  ignorePlaylistParsingErrors: !1,
  loader: cy,
  // loader: FetchLoader,
  fLoader: void 0,
  // used by fragment-loader
  pLoader: void 0,
  // used by playlist-loader
  xhrSetup: void 0,
  // used by xhr-loader
  licenseXhrSetup: void 0,
  // used by eme-controller
  licenseResponseCallback: void 0,
  // used by eme-controller
  abrController: xC,
  bufferController: hR,
  capLevelController: sh,
  errorController: bC,
  fpsController: hI,
  stretchShortVideoTrack: !1,
  // used by mp4-remuxer
  maxAudioFramesDrift: 1,
  // used by mp4-remuxer
  forceKeyFrameOnDiscontinuity: !0,
  // used by ts-demuxer
  abrEwmaFastLive: 3,
  // used by abr-controller
  abrEwmaSlowLive: 9,
  // used by abr-controller
  abrEwmaFastVoD: 3,
  // used by abr-controller
  abrEwmaSlowVoD: 9,
  // used by abr-controller
  abrEwmaDefaultEstimate: 5e5,
  // 500 kbps  // used by abr-controller
  abrEwmaDefaultEstimateMax: 5e6,
  // 5 mbps
  abrBandWidthFactor: 0.95,
  // used by abr-controller
  abrBandWidthUpFactor: 0.7,
  // used by abr-controller
  abrMaxWithRealBitrate: !1,
  // used by abr-controller
  maxStarvationDelay: 4,
  // used by abr-controller
  maxLoadingDelay: 4,
  // used by abr-controller
  minAutoBitrate: 0,
  // used by hls
  emeEnabled: !1,
  // used by eme-controller
  widevineLicenseUrl: void 0,
  // used by eme-controller
  drmSystems: {},
  // used by eme-controller
  drmSystemOptions: {},
  // used by eme-controller
  requestMediaKeySystemAccessFunc: l_,
  // used by eme-controller
  requireKeySystemAccessOnStart: !1,
  // used by eme-controller
  testBandwidth: !0,
  progressive: !1,
  lowLatencyMode: !0,
  cmcd: void 0,
  enableDateRangeMetadataCues: !0,
  enableEmsgMetadataCues: !0,
  enableEmsgKLVMetadata: !1,
  enableID3MetadataCues: !0,
  enableInterstitialPlayback: !0,
  interstitialAppendInPlace: !0,
  interstitialLiveLookAhead: 10,
  useMediaCapabilities: !0,
  preserveManualLevelOnError: !1,
  certLoadPolicy: {
    default: o5
  },
  keyLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 8e3,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 1,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 2e4,
        backoff: "linear"
      },
      errorRetry: {
        maxNumRetry: 8,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 2e4,
        backoff: "linear"
      }
    }
  },
  manifestLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1 / 0,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 1,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  playlistLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 2,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  fragLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 12e4,
      timeoutRetry: {
        maxNumRetry: 4,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 6,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  steeringManifestLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 2e4,
      timeoutRetry: {
        maxNumRetry: 2,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 1,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  interstitialAssetListLoadPolicy: {
    default: {
      maxTimeToFirstByteMs: 1e4,
      maxLoadTimeMs: 3e4,
      timeoutRetry: {
        maxNumRetry: 0,
        retryDelayMs: 0,
        maxRetryDelayMs: 0
      },
      errorRetry: {
        maxNumRetry: 0,
        retryDelayMs: 1e3,
        maxRetryDelayMs: 8e3
      }
    }
  },
  // These default settings are deprecated in favor of the above policies
  // and are maintained for backwards compatibility
  manifestLoadingTimeOut: 1e4,
  manifestLoadingMaxRetry: 1,
  manifestLoadingRetryDelay: 1e3,
  manifestLoadingMaxRetryTimeout: 64e3,
  levelLoadingTimeOut: 1e4,
  levelLoadingMaxRetry: 4,
  levelLoadingRetryDelay: 1e3,
  levelLoadingMaxRetryTimeout: 64e3,
  fragLoadingTimeOut: 2e4,
  fragLoadingMaxRetry: 6,
  fragLoadingRetryDelay: 1e3,
  fragLoadingMaxRetryTimeout: 64e3
}, c5()), {}, {
  subtitleStreamController: TI,
  subtitleTrackController: pI,
  timelineController: zI,
  audioStreamController: oR,
  audioTrackController: lR,
  emeController: Ar,
  cmcdController: lI,
  contentSteeringController: dI,
  interstitialsController: SI
});
function c5() {
  return {
    cueHandler: JI,
    // used by timeline-controller
    enableWebVTT: !0,
    // used by timeline-controller
    enableIMSC1: !0,
    // used by timeline-controller
    enableCEA708Captions: !0,
    // used by timeline-controller
    captionsTextTrack1Label: "English",
    // used by timeline-controller
    captionsTextTrack1LanguageCode: "en",
    // used by timeline-controller
    captionsTextTrack2Label: "Spanish",
    // used by timeline-controller
    captionsTextTrack2LanguageCode: "es",
    // used by timeline-controller
    captionsTextTrack3Label: "Unknown CC",
    // used by timeline-controller
    captionsTextTrack3LanguageCode: "",
    // used by timeline-controller
    captionsTextTrack4Label: "Unknown CC",
    // used by timeline-controller
    captionsTextTrack4LanguageCode: "",
    // used by timeline-controller
    renderTextTracksNatively: !0
  };
}
function d5(r, e, t) {
  if ((e.liveSyncDurationCount || e.liveMaxLatencyDurationCount) && (e.liveSyncDuration || e.liveMaxLatencyDuration))
    throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  if (e.liveMaxLatencyDurationCount !== void 0 && (e.liveSyncDurationCount === void 0 || e.liveMaxLatencyDurationCount <= e.liveSyncDurationCount))
    throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  if (e.liveMaxLatencyDuration !== void 0 && (e.liveSyncDuration === void 0 || e.liveMaxLatencyDuration <= e.liveSyncDuration))
    throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  const i = $c(r), s = ["manifest", "level", "frag"], n = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  return s.forEach((a) => {
    const o = `${a === "level" ? "playlist" : a}LoadPolicy`, c = e[o] === void 0, l = [];
    n.forEach((d) => {
      const h = `${a}Loading${d}`, u = e[h];
      if (u !== void 0 && c) {
        l.push(h);
        const f = i[o].default;
        switch (e[o] = {
          default: f
        }, d) {
          case "TimeOut":
            f.maxLoadTimeMs = u, f.maxTimeToFirstByteMs = u;
            break;
          case "MaxRetry":
            f.errorRetry.maxNumRetry = u, f.timeoutRetry.maxNumRetry = u;
            break;
          case "RetryDelay":
            f.errorRetry.retryDelayMs = u, f.timeoutRetry.retryDelayMs = u;
            break;
          case "MaxRetryTimeout":
            f.errorRetry.maxRetryDelayMs = u, f.timeoutRetry.maxRetryDelayMs = u;
            break;
        }
      }
    }), l.length && t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${Ze(e[o])}`);
  }), we(we({}, i), e);
}
function $c(r) {
  return r && typeof r == "object" ? Array.isArray(r) ? r.map($c) : Object.keys(r).reduce((e, t) => (e[t] = $c(r[t]), e), {}) : r;
}
function h5(r, e) {
  const t = r.loader;
  t !== tm && t !== cy ? (e.log("[config]: Custom loader detected, cannot enable progressive streaming"), r.progressive = !1) : qI() && (r.loader = tm, r.progressive = !0, r.enableSoftwareAES = !0, e.log("[config]: Progressive streaming enabled, using FetchLoader"));
}
const Fa = 2, u5 = 0.1, f5 = 0.05, p5 = 100;
class m5 extends r_ {
  constructor(e, t) {
    super("gap-controller", e.logger), this.hls = void 0, this.fragmentTracker = void 0, this.media = null, this.mediaSource = void 0, this.nudgeRetry = 0, this.stallReported = !1, this.stalled = null, this.moved = !1, this.seeking = !1, this.buffered = {}, this.lastCurrentTime = 0, this.ended = 0, this.waiting = 0, this.onMediaPlaying = () => {
      this.ended = 0, this.waiting = 0;
    }, this.onMediaWaiting = () => {
      var i;
      (i = this.media) != null && i.seeking || (this.waiting = self.performance.now(), this.tick());
    }, this.onMediaEnded = () => {
      if (this.hls) {
        var i;
        this.ended = ((i = this.media) == null ? void 0 : i.currentTime) || 1, this.hls.trigger(T.MEDIA_ENDED, {
          stalled: !1
        });
      }
    }, this.hls = e, this.fragmentTracker = t, this.registerListeners();
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e && (e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.BUFFER_APPENDED, this.onBufferAppended, this));
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.BUFFER_APPENDED, this.onBufferAppended, this));
  }
  destroy() {
    super.destroy(), this.unregisterListeners(), this.media = this.hls = this.fragmentTracker = null, this.mediaSource = void 0;
  }
  onMediaAttached(e, t) {
    this.setInterval(p5), this.mediaSource = t.mediaSource;
    const i = this.media = t.media;
    bt(i, "playing", this.onMediaPlaying), bt(i, "waiting", this.onMediaWaiting), bt(i, "ended", this.onMediaEnded);
  }
  onMediaDetaching(e, t) {
    this.clearInterval();
    const {
      media: i
    } = this;
    i && (Ft(i, "playing", this.onMediaPlaying), Ft(i, "waiting", this.onMediaWaiting), Ft(i, "ended", this.onMediaEnded), this.media = null), this.mediaSource = void 0;
  }
  onBufferAppended(e, t) {
    this.buffered = t.timeRanges;
  }
  get hasBuffered() {
    return Object.keys(this.buffered).length > 0;
  }
  tick() {
    var e;
    if (!((e = this.media) != null && e.readyState) || !this.hasBuffered)
      return;
    const t = this.media.currentTime;
    this.poll(t, this.lastCurrentTime), this.lastCurrentTime = t;
  }
  /**
   * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
   * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
   *
   * @param lastCurrentTime - Previously read playhead position
   */
  poll(e, t) {
    var i, s;
    const n = (i = this.hls) == null ? void 0 : i.config;
    if (!n)
      return;
    const a = this.media;
    if (!a)
      return;
    const {
      seeking: o
    } = a, c = this.seeking && !o, l = !this.seeking && o, d = a.paused && !o || a.ended || a.playbackRate === 0;
    if (this.seeking = o, e !== t) {
      t && (this.ended = 0), this.moved = !0, o || (this.nudgeRetry = 0, n.nudgeOnVideoHole && !d && e > t && this.nudgeOnVideoHole(e, t)), this.waiting === 0 && this.stallResolved(e);
      return;
    }
    if (l || c) {
      c && this.stallResolved(e);
      return;
    }
    if (d) {
      this.nudgeRetry = 0, this.stallResolved(e), !this.ended && a.ended && this.hls && (this.ended = e || 1, this.hls.trigger(T.MEDIA_ENDED, {
        stalled: !1
      }));
      return;
    }
    if (!ce.getBuffered(a).length) {
      this.nudgeRetry = 0;
      return;
    }
    const h = ce.bufferInfo(a, e, 0), u = h.nextStart || 0, f = this.fragmentTracker;
    if (o && f && this.hls) {
      const A = im(this.hls.inFlightFragments, e), C = h.len > Fa, I = !u || A || u - e > Fa && !f.getPartialFragment(e);
      if (C || I)
        return;
      this.moved = !1;
    }
    const p = (s = this.hls) == null ? void 0 : s.latestLevelDetails;
    if (!this.moved && this.stalled !== null && f) {
      if (!(h.len > 0) && !u)
        return;
      const C = Math.max(u, h.start || 0) - e, L = !!(p != null && p.live) ? p.targetduration * 2 : Fa, R = la(e, f);
      if (C > 0 && (C <= L || R)) {
        a.paused || this._trySkipBufferHole(R);
        return;
      }
    }
    const m = n.detectStallWithCurrentTimeMs, g = self.performance.now(), x = this.waiting;
    let _ = this.stalled;
    if (_ === null)
      if (x > 0 && g - x < m)
        _ = this.stalled = x;
      else {
        this.stalled = g;
        return;
      }
    const v = g - _;
    if (!o && (v >= m || x) && this.hls) {
      var E;
      if (((E = this.mediaSource) == null ? void 0 : E.readyState) === "ended" && !(p != null && p.live) && Math.abs(e - ((p == null ? void 0 : p.edge) || 0)) < 1) {
        if (this.ended)
          return;
        this.ended = e || 1, this.hls.trigger(T.MEDIA_ENDED, {
          stalled: !0
        });
        return;
      }
      if (this._reportStall(h), !this.media || !this.hls)
        return;
    }
    const b = ce.bufferInfo(a, e, n.maxBufferHole);
    this._tryFixBufferStall(b, v, e);
  }
  stallResolved(e) {
    const t = this.stalled;
    if (t && this.hls && (this.stalled = null, this.stallReported)) {
      const i = self.performance.now() - t;
      this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`), this.stallReported = !1, this.waiting = 0, this.hls.trigger(T.STALL_RESOLVED, {});
    }
  }
  nudgeOnVideoHole(e, t) {
    var i;
    const s = this.buffered.video;
    if (this.hls && this.media && this.fragmentTracker && (i = this.buffered.audio) != null && i.length && s && s.length > 1 && e > s.end(0)) {
      const n = ce.bufferedInfo(ce.timeRangesToArray(this.buffered.audio), e, 0);
      if (n.len > 1 && t >= n.start) {
        const a = ce.timeRangesToArray(s), o = ce.bufferedInfo(a, t, 0).bufferedIndex;
        if (o > -1 && o < a.length - 1) {
          const c = ce.bufferedInfo(a, e, 0).bufferedIndex, l = a[o].end, d = a[o + 1].start;
          if ((c === -1 || c > o) && d - l < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
          e - l < 2) {
            const h = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${c}`);
            this.warn(h.message), this.media.currentTime += 1e-6;
            let u = la(e, this.fragmentTracker);
            u && "fragment" in u ? u = u.fragment : u || (u = void 0);
            const f = ce.bufferInfo(this.media, e, 0);
            this.hls.trigger(T.ERROR, {
              type: ie.MEDIA_ERROR,
              details: V.BUFFER_SEEK_OVER_HOLE,
              fatal: !1,
              error: h,
              reason: h.message,
              frag: u,
              buffer: f.len,
              bufferInfo: f
            });
          }
        }
      }
    }
  }
  /**
   * Detects and attempts to fix known buffer stalling issues.
   * @param bufferInfo - The properties of the current buffer.
   * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
   * @private
   */
  _tryFixBufferStall(e, t, i) {
    var s, n;
    const {
      fragmentTracker: a,
      media: o
    } = this, c = (s = this.hls) == null ? void 0 : s.config;
    if (!o || !a || !c)
      return;
    const l = (n = this.hls) == null ? void 0 : n.latestLevelDetails, d = la(i, a);
    if ((d || l != null && l.live && i < l.fragmentStart) && (this._trySkipBufferHole(d) || !this.media))
      return;
    const h = e.buffered, u = this.adjacentTraversal(e, i);
    (h && h.length > 1 && e.len > c.maxBufferHole || e.nextStart && (e.nextStart - i < c.maxBufferHole || u)) && (t > c.highBufferWatchdogPeriod * 1e3 || this.waiting) && (this.warn("Trying to nudge playhead over buffer-hole"), this._tryNudgeBuffer(e));
  }
  adjacentTraversal(e, t) {
    const i = this.fragmentTracker, s = e.nextStart;
    if (i && s) {
      const n = i.getFragAtPos(t, te.MAIN), a = i.getFragAtPos(s, te.MAIN);
      if (n && a)
        return a.sn - n.sn < 2;
    }
    return !1;
  }
  /**
   * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
   * @param bufferLen - The playhead distance from the end of the current buffer segment.
   * @private
   */
  _reportStall(e) {
    const {
      hls: t,
      media: i,
      stallReported: s,
      stalled: n
    } = this;
    if (!s && n !== null && i && t) {
      this.stallReported = !0;
      const a = new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ze(e)})`);
      this.warn(a.message), t.trigger(T.ERROR, {
        type: ie.MEDIA_ERROR,
        details: V.BUFFER_STALLED_ERROR,
        fatal: !1,
        error: a,
        buffer: e.len,
        bufferInfo: e,
        stalled: {
          start: n
        }
      });
    }
  }
  /**
   * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
   * @param appended - The fragment or part found at the current time (where playback is stalling).
   * @private
   */
  _trySkipBufferHole(e) {
    var t;
    const {
      fragmentTracker: i,
      media: s
    } = this, n = (t = this.hls) == null ? void 0 : t.config;
    if (!s || !i || !n)
      return 0;
    const a = s.currentTime, o = ce.bufferInfo(s, a, 0), c = a < o.start ? o.start : o.nextStart;
    if (c && this.hls) {
      const d = o.len <= n.maxBufferHole, h = o.len > 0 && o.len < 1 && s.readyState < 3, u = c - a;
      if (u > 0 && (d || h)) {
        if (u > n.maxBufferHole) {
          let p = !1;
          if (a === 0) {
            const m = i.getAppendedFrag(0, te.MAIN);
            m && c < m.end && (p = !0);
          }
          if (!p && e) {
            var l;
            if (!((l = this.hls.loadLevelObj) != null && l.details) || im(this.hls.inFlightFragments, c))
              return 0;
            let g = !1, x = e.end;
            for (; x < c; ) {
              const _ = la(x, i);
              if (_)
                x += _.duration;
              else {
                g = !0;
                break;
              }
            }
            if (g)
              return 0;
          }
        }
        const f = Math.max(c + f5, a + u5);
        if (this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`), this.moved = !0, s.currentTime = f, !(e != null && e.gap)) {
          const p = new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`), m = {
            type: ie.MEDIA_ERROR,
            details: V.BUFFER_SEEK_OVER_HOLE,
            fatal: !1,
            error: p,
            reason: p.message,
            buffer: o.len,
            bufferInfo: o
          };
          e && ("fragment" in e ? m.part = e : m.frag = e), this.hls.trigger(T.ERROR, m);
        }
        return f;
      }
    }
    return 0;
  }
  /**
   * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
   * @private
   */
  _tryNudgeBuffer(e) {
    const {
      hls: t,
      media: i,
      nudgeRetry: s
    } = this, n = t == null ? void 0 : t.config;
    if (!i || !n)
      return 0;
    const a = i.currentTime;
    if (this.nudgeRetry++, s < n.nudgeMaxRetry) {
      const o = a + (s + 1) * n.nudgeOffset, c = new Error(`Nudging 'currentTime' from ${a} to ${o}`);
      this.warn(c.message), i.currentTime = o, t.trigger(T.ERROR, {
        type: ie.MEDIA_ERROR,
        details: V.BUFFER_NUDGE_ON_STALL,
        error: c,
        fatal: !1,
        buffer: e.len,
        bufferInfo: e
      });
    } else {
      const o = new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);
      this.error(o.message), t.trigger(T.ERROR, {
        type: ie.MEDIA_ERROR,
        details: V.BUFFER_STALLED_ERROR,
        error: o,
        fatal: !0,
        buffer: e.len,
        bufferInfo: e
      });
    }
  }
}
function im(r, e) {
  const t = sm(r.main);
  if (t && t.start <= e)
    return t;
  const i = sm(r.audio);
  return i && i.start <= e ? i : null;
}
function sm(r) {
  if (!r)
    return null;
  switch (r.state) {
    case K.IDLE:
    case K.STOPPED:
    case K.ENDED:
    case K.ERROR:
      return null;
  }
  return r.frag;
}
function la(r, e) {
  return e.getAppendedFrag(r, te.MAIN) || e.getPartialFragment(r);
}
const g5 = 0.25;
function Kc() {
  if (!(typeof self > "u"))
    return self.VTTCue || self.TextTrackCue;
}
function O0(r, e, t, i, s) {
  let n = new r(e, t, "");
  try {
    n.value = i, s && (n.type = s);
  } catch {
    n = new r(e, t, Ze(s ? we({
      type: s
    }, i) : i));
  }
  return n;
}
const ca = (() => {
  const r = Kc();
  try {
    r && new r(0, Number.POSITIVE_INFINITY, "");
  } catch {
    return Number.MAX_VALUE;
  }
  return Number.POSITIVE_INFINITY;
})();
class _5 {
  constructor(e) {
    this.hls = void 0, this.id3Track = null, this.media = null, this.dateRangeCuesAppended = {}, this.removeCues = !0, this.assetCue = void 0, this.onEventCueEnter = () => {
      this.hls && this.hls.trigger(T.EVENT_CUE_ENTER, {});
    }, this.hls = e, this._registerListeners();
  }
  destroy() {
    this._unregisterListeners(), this.id3Track = null, this.media = null, this.dateRangeCuesAppended = {}, this.hls = this.onEventCueEnter = null;
  }
  _registerListeners() {
    const {
      hls: e
    } = this;
    e && (e.on(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this), e.on(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.on(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.on(T.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this));
  }
  _unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (e.off(T.MEDIA_ATTACHING, this.onMediaAttaching, this), e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this), e.off(T.BUFFER_FLUSHING, this.onBufferFlushing, this), e.off(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.off(T.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this));
  }
  // Add ID3 metatadata text track.
  onMediaAttaching(e, t) {
    var i;
    this.media = t.media, ((i = t.overrides) == null ? void 0 : i.cueRemoval) === !1 && (this.removeCues = !1);
  }
  onMediaAttached() {
    var e;
    const t = (e = this.hls) == null ? void 0 : e.latestLevelDetails;
    t && this.updateDateRangeCues(t);
  }
  onMediaDetaching(e, t) {
    this.media = null, !t.transferMedia && (this.id3Track && (this.removeCues && mr(this.id3Track, this.onEventCueEnter), this.id3Track = null), this.dateRangeCuesAppended = {});
  }
  onManifestLoading() {
    this.dateRangeCuesAppended = {};
  }
  createTrack(e) {
    const t = this.getID3Track(e.textTracks);
    return t.mode = "hidden", t;
  }
  getID3Track(e) {
    if (this.media) {
      for (let t = 0; t < e.length; t++) {
        const i = e[t];
        if (i.kind === "metadata" && i.label === "id3")
          return Q_(i, this.media), i;
      }
      return this.media.addTextTrack("metadata", "id3");
    }
  }
  onFragParsingMetadata(e, t) {
    if (!this.media || !this.hls)
      return;
    const {
      enableEmsgMetadataCues: i,
      enableID3MetadataCues: s
    } = this.hls.config;
    if (!i && !s)
      return;
    const {
      samples: n
    } = t;
    this.id3Track || (this.id3Track = this.createTrack(this.media));
    const a = Kc();
    if (a)
      for (let o = 0; o < n.length; o++) {
        const c = n[o].type;
        if (c === Ht.emsg && !i || !s)
          continue;
        const l = A_(n[o].data), d = n[o].pts;
        let h = d + n[o].duration;
        h > ca && (h = ca), h - d <= 0 && (h = d + g5);
        for (let f = 0; f < l.length; f++) {
          const p = l[f];
          if (!C_(p)) {
            this.updateId3CueEnds(d, c);
            const m = O0(a, d, h, p, c);
            m && this.id3Track.addCue(m);
          }
        }
      }
  }
  updateId3CueEnds(e, t) {
    var i;
    const s = (i = this.id3Track) == null ? void 0 : i.cues;
    if (s)
      for (let n = s.length; n--; ) {
        const a = s[n];
        a.type === t && a.startTime < e && a.endTime === ca && (a.endTime = e);
      }
  }
  onBufferFlushing(e, {
    startOffset: t,
    endOffset: i,
    type: s
  }) {
    const {
      id3Track: n,
      hls: a
    } = this;
    if (!a)
      return;
    const {
      config: {
        enableEmsgMetadataCues: o,
        enableID3MetadataCues: c
      }
    } = a;
    if (n && (o || c)) {
      let l;
      s === "audio" ? l = (d) => d.type === Ht.audioId3 && c : s === "video" ? l = (d) => d.type === Ht.emsg && o : l = (d) => d.type === Ht.audioId3 && c || d.type === Ht.emsg && o, Hc(n, t, i, l);
    }
  }
  onLevelUpdated(e, {
    details: t
  }) {
    this.updateDateRangeCues(t, !0);
  }
  onLevelPtsUpdated(e, t) {
    Math.abs(t.drift) > 0.01 && this.updateDateRangeCues(t.details);
  }
  updateDateRangeCues(e, t) {
    if (!this.hls || !this.media)
      return;
    const {
      assetPlayerId: i,
      timelineOffset: s,
      enableDateRangeMetadataCues: n,
      interstitialsController: a
    } = this.hls.config;
    if (!n)
      return;
    const o = Kc();
    if (i && s && !a) {
      const {
        fragmentStart: m,
        fragmentEnd: g
      } = e;
      let x = this.assetCue;
      x ? (x.startTime = m, x.endTime = g) : o && (x = this.assetCue = O0(o, m, g, {
        assetPlayerId: this.hls.config.assetPlayerId
      }, "hlsjs.interstitial.asset"), x && (x.id = i, this.id3Track || (this.id3Track = this.createTrack(this.media)), this.id3Track.addCue(x), x.addEventListener("enter", this.onEventCueEnter)));
    }
    if (!e.hasProgramDateTime)
      return;
    const {
      id3Track: c
    } = this, {
      dateRanges: l
    } = e, d = Object.keys(l);
    let h = this.dateRangeCuesAppended;
    if (c && t) {
      var u;
      if ((u = c.cues) != null && u.length) {
        const m = Object.keys(h).filter((g) => !d.includes(g));
        for (let g = m.length; g--; ) {
          var f;
          const x = m[g], _ = (f = h[x]) == null ? void 0 : f.cues;
          delete h[x], _ && Object.keys(_).forEach((v) => {
            const E = _[v];
            if (E) {
              E.removeEventListener("enter", this.onEventCueEnter);
              try {
                c.removeCue(E);
              } catch {
              }
            }
          });
        }
      } else
        h = this.dateRangeCuesAppended = {};
    }
    const p = e.fragments[e.fragments.length - 1];
    if (!(d.length === 0 || !q(p == null ? void 0 : p.programDateTime))) {
      this.id3Track || (this.id3Track = this.createTrack(this.media));
      for (let m = 0; m < d.length; m++) {
        const g = d[m], x = l[g], _ = x.startTime, v = h[g], E = (v == null ? void 0 : v.cues) || {};
        let b = (v == null ? void 0 : v.durationKnown) || !1, A = ca;
        const {
          duration: C,
          endDate: I
        } = x;
        if (I && C !== null)
          A = _ + C, b = !0;
        else if (x.endOnNext && !b) {
          const R = d.reduce((D, M) => {
            if (M !== x.id) {
              const w = l[M];
              if (w.class === x.class && w.startDate > x.startDate && (!D || x.startDate < D.startDate))
                return w;
            }
            return D;
          }, null);
          R && (A = R.startTime, b = !0);
        }
        const L = Object.keys(x.attr);
        for (let R = 0; R < L.length; R++) {
          const D = L[R];
          if (!OC(D))
            continue;
          const M = E[D];
          if (M)
            b && !(v != null && v.durationKnown) ? M.endTime = A : Math.abs(M.startTime - _) > 0.01 && (M.startTime = _, M.endTime = A);
          else if (o) {
            let w = x.attr[D];
            NC(D) && (w = Vg(w));
            const H = O0(o, _, A, {
              key: D,
              data: w
            }, Ht.dateRange);
            H && (H.id = g, this.id3Track.addCue(H), E[D] = H, a && (D === "X-ASSET-LIST" || D === "X-ASSET-URL") && H.addEventListener("enter", this.onEventCueEnter));
          }
        }
        h[g] = {
          cues: E,
          dateRange: x,
          durationKnown: b
        };
      }
    }
  }
}
class y5 {
  constructor(e) {
    this.hls = void 0, this.config = void 0, this.media = null, this.currentTime = 0, this.stallCount = 0, this._latency = null, this._targetLatencyUpdated = !1, this.onTimeupdate = () => {
      const {
        media: t
      } = this, i = this.levelDetails;
      if (!t || !i)
        return;
      this.currentTime = t.currentTime;
      const s = this.computeLatency();
      if (s === null)
        return;
      this._latency = s;
      const {
        lowLatencyMode: n,
        maxLiveSyncPlaybackRate: a
      } = this.config;
      if (!n || a === 1 || !i.live)
        return;
      const o = this.targetLatency;
      if (o === null)
        return;
      const c = s - o, l = Math.min(this.maxLatency, o + i.targetduration);
      if (c < l && c > 0.05 && this.forwardBufferLength > 1) {
        const h = Math.min(2, Math.max(1, a)), u = Math.round(2 / (1 + Math.exp(-0.75 * c - this.edgeStalled)) * 20) / 20, f = Math.min(h, Math.max(1, u));
        this.changeMediaPlaybackRate(t, f);
      } else t.playbackRate !== 1 && t.playbackRate !== 0 && this.changeMediaPlaybackRate(t, 1);
    }, this.hls = e, this.config = e.config, this.registerListeners();
  }
  get levelDetails() {
    var e;
    return ((e = this.hls) == null ? void 0 : e.latestLevelDetails) || null;
  }
  get latency() {
    return this._latency || 0;
  }
  get maxLatency() {
    const {
      config: e
    } = this;
    if (e.liveMaxLatencyDuration !== void 0)
      return e.liveMaxLatencyDuration;
    const t = this.levelDetails;
    return t ? e.liveMaxLatencyDurationCount * t.targetduration : 0;
  }
  get targetLatency() {
    const e = this.levelDetails;
    if (e === null || this.hls === null)
      return null;
    const {
      holdBack: t,
      partHoldBack: i,
      targetduration: s
    } = e, {
      liveSyncDuration: n,
      liveSyncDurationCount: a,
      lowLatencyMode: o
    } = this.config, c = this.hls.userConfig;
    let l = o && i || t;
    (this._targetLatencyUpdated || c.liveSyncDuration || c.liveSyncDurationCount || l === 0) && (l = n !== void 0 ? n : a * s);
    const d = s;
    return l + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, d);
  }
  set targetLatency(e) {
    this.stallCount = 0, this.config.liveSyncDuration = e, this._targetLatencyUpdated = !0;
  }
  get liveSyncPosition() {
    const e = this.estimateLiveEdge(), t = this.targetLatency;
    if (e === null || t === null)
      return null;
    const i = this.levelDetails;
    if (i === null)
      return null;
    const s = i.edge, n = e - t - this.edgeStalled, a = s - i.totalduration, o = s - (this.config.lowLatencyMode && i.partTarget || i.targetduration);
    return Math.min(Math.max(a, n), o);
  }
  get drift() {
    const e = this.levelDetails;
    return e === null ? 1 : e.drift;
  }
  get edgeStalled() {
    const e = this.levelDetails;
    if (e === null)
      return 0;
    const t = (this.config.lowLatencyMode && e.partTarget || e.targetduration) * 3;
    return Math.max(e.age - t, 0);
  }
  get forwardBufferLength() {
    const {
      media: e
    } = this, t = this.levelDetails;
    if (!e || !t)
      return 0;
    const i = e.buffered.length;
    return (i ? e.buffered.end(i - 1) : t.edge) - this.currentTime;
  }
  destroy() {
    this.unregisterListeners(), this.onMediaDetaching(), this.hls = null;
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e && (e.on(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.on(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.on(T.ERROR, this.onError, this));
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e && (e.off(T.MEDIA_ATTACHED, this.onMediaAttached, this), e.off(T.MEDIA_DETACHING, this.onMediaDetaching, this), e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.LEVEL_UPDATED, this.onLevelUpdated, this), e.off(T.ERROR, this.onError, this));
  }
  onMediaAttached(e, t) {
    this.media = t.media, this.media.addEventListener("timeupdate", this.onTimeupdate);
  }
  onMediaDetaching() {
    this.media && (this.media.removeEventListener("timeupdate", this.onTimeupdate), this.media = null);
  }
  onManifestLoading() {
    this._latency = null, this.stallCount = 0;
  }
  onLevelUpdated(e, {
    details: t
  }) {
    t.advanced && this.onTimeupdate(), !t.live && this.media && this.media.removeEventListener("timeupdate", this.onTimeupdate);
  }
  onError(e, t) {
    var i;
    t.details === V.BUFFER_STALLED_ERROR && (this.stallCount++, this.hls && (i = this.levelDetails) != null && i.live && this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"));
  }
  changeMediaPlaybackRate(e, t) {
    var i, s;
    e.playbackRate !== t && ((i = this.hls) == null || i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s = this.targetLatency) == null ? void 0 : s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`), e.playbackRate = t);
  }
  estimateLiveEdge() {
    const e = this.levelDetails;
    return e === null ? null : e.edge + e.age;
  }
  computeLatency() {
    const e = this.estimateLiveEdge();
    return e === null ? null : e - this.currentTime;
  }
}
class x5 extends ih {
  constructor(e, t) {
    super(e, "level-controller"), this._levels = [], this._firstLevel = -1, this._maxAutoLevel = -1, this._startLevel = void 0, this.currentLevel = null, this.currentLevelIndex = -1, this.manualLevelIndex = -1, this.steering = void 0, this.onParsedComplete = void 0, this.steering = t, this._registerListeners();
  }
  _registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.on(T.LEVEL_LOADED, this.onLevelLoaded, this), e.on(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.on(T.FRAG_BUFFERED, this.onFragBuffered, this), e.on(T.ERROR, this.onError, this);
  }
  _unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.MANIFEST_LOADED, this.onManifestLoaded, this), e.off(T.LEVEL_LOADED, this.onLevelLoaded, this), e.off(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.off(T.FRAG_BUFFERED, this.onFragBuffered, this), e.off(T.ERROR, this.onError, this);
  }
  destroy() {
    this._unregisterListeners(), this.steering = null, this.resetLevels(), super.destroy();
  }
  stopLoad() {
    this._levels.forEach((t) => {
      t.loadError = 0, t.fragmentError = 0;
    }), super.stopLoad();
  }
  resetLevels() {
    this._startLevel = void 0, this.manualLevelIndex = -1, this.currentLevelIndex = -1, this.currentLevel = null, this._levels = [], this._maxAutoLevel = -1;
  }
  onManifestLoading(e, t) {
    this.resetLevels();
  }
  onManifestLoaded(e, t) {
    const i = this.hls.config.preferManagedMediaSource, s = [], n = {}, a = {};
    let o = !1, c = !1, l = !1;
    t.levels.forEach((d) => {
      const h = d.attrs;
      let {
        audioCodec: u,
        videoCodec: f
      } = d;
      u && (d.audioCodec = u = to(u, i) || void 0), f && (f = d.videoCodec = eC(f));
      const {
        width: p,
        height: m,
        unknownCodecs: g
      } = d;
      let x = g ? g.length : 0;
      if (g)
        for (let R = x; R--; ) {
          const D = g[R];
          this.isAudioSupported(D) ? (d.audioCodec = u = u ? `${u},${D}` : D, x--, kr.audio[u.substring(0, 4)] = 2) : this.isVideoSupported(D) && (d.videoCodec = f = f ? `${f},${D}` : D, x--, kr.video[f.substring(0, 4)] = 2);
        }
      if (o || (o = !!(p && m)), c || (c = !!f), l || (l = !!u), x || u && !this.isAudioSupported(u) || f && !this.isVideoSupported(f)) {
        this.log(`Some or all CODECS not supported "${h.CODECS}"`);
        return;
      }
      const {
        CODECS: _,
        "FRAME-RATE": v,
        "HDCP-LEVEL": E,
        "PATHWAY-ID": b,
        RESOLUTION: A,
        "VIDEO-RANGE": C
      } = h, L = `${`${b || "."}-`}${d.bitrate}-${A}-${v}-${_}-${C}-${E}`;
      if (n[L])
        if (n[L].uri !== d.url && !d.attrs["PATHWAY-ID"]) {
          const R = a[L] += 1;
          d.attrs["PATHWAY-ID"] = new Array(R + 1).join(".");
          const D = this.createLevel(d);
          n[L] = D, s.push(D);
        } else
          n[L].addGroupId("audio", h.AUDIO), n[L].addGroupId("text", h.SUBTITLES);
      else {
        const R = this.createLevel(d);
        n[L] = R, a[L] = 1, s.push(R);
      }
    }), this.filterAndSortMediaOptions(s, t, o, c, l);
  }
  createLevel(e) {
    const t = new En(e), i = e.supplemental;
    if (i != null && i.videoCodec && !this.isVideoSupported(i.videoCodec)) {
      const s = new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);
      this.log(s.message), t.supportedResult = Jg(s, []);
    }
    return t;
  }
  isAudioSupported(e) {
    return Lc(e, "audio", this.hls.config.preferManagedMediaSource);
  }
  isVideoSupported(e) {
    return Lc(e, "video", this.hls.config.preferManagedMediaSource);
  }
  filterAndSortMediaOptions(e, t, i, s, n) {
    let a = [], o = [], c = e;
    if ((i || s) && n && (c = c.filter(({
      videoCodec: g,
      videoRange: x,
      width: _,
      height: v
    }) => (!!g || !!(_ && v)) && dC(x))), c.length === 0) {
      Promise.resolve().then(() => {
        if (this.hls) {
          let g = "no level with compatible codecs found in manifest", x = g;
          t.levels.length && (x = `one or more CODECS in variant not supported: ${Ze(t.levels.map((v) => v.attrs.CODECS).filter((v, E, b) => b.indexOf(v) === E))}`, this.warn(x), g += ` (${x})`);
          const _ = new Error(g);
          this.hls.trigger(T.ERROR, {
            type: ie.MEDIA_ERROR,
            details: V.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
            fatal: !0,
            url: t.url,
            error: _,
            reason: x
          });
        }
      });
      return;
    }
    t.audioTracks && (a = t.audioTracks.filter((g) => !g.audioCodec || this.isAudioSupported(g.audioCodec)), rm(a)), t.subtitles && (o = t.subtitles, rm(o));
    const l = c.slice(0);
    c.sort((g, x) => {
      if (g.attrs["HDCP-LEVEL"] !== x.attrs["HDCP-LEVEL"])
        return (g.attrs["HDCP-LEVEL"] || "") > (x.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
      if (i && g.height !== x.height)
        return g.height - x.height;
      if (g.frameRate !== x.frameRate)
        return g.frameRate - x.frameRate;
      if (g.videoRange !== x.videoRange)
        return io.indexOf(g.videoRange) - io.indexOf(x.videoRange);
      if (g.videoCodec !== x.videoCodec) {
        const _ = Qf(g.videoCodec), v = Qf(x.videoCodec);
        if (_ !== v)
          return v - _;
      }
      if (g.uri === x.uri && g.codecSet !== x.codecSet) {
        const _ = eo(g.codecSet), v = eo(x.codecSet);
        if (_ !== v)
          return v - _;
      }
      return g.averageBitrate !== x.averageBitrate ? g.averageBitrate - x.averageBitrate : 0;
    });
    let d = l[0];
    if (this.steering && (c = this.steering.filterParsedLevels(c), c.length !== l.length)) {
      for (let g = 0; g < l.length; g++)
        if (l[g].pathwayId === c[0].pathwayId) {
          d = l[g];
          break;
        }
    }
    this._levels = c;
    for (let g = 0; g < c.length; g++)
      if (c[g] === d) {
        var h;
        this._firstLevel = g;
        const x = d.bitrate, _ = this.hls.bandwidthEstimate;
        if (this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${x}`), ((h = this.hls.userConfig) == null ? void 0 : h.abrEwmaDefaultEstimate) === void 0) {
          const v = Math.min(x, this.hls.config.abrEwmaDefaultEstimateMax);
          v > _ && _ === this.hls.abrEwmaDefaultEstimate && (this.hls.bandwidthEstimate = v);
        }
        break;
      }
    const u = n && !s, f = this.hls.config, p = !!(f.audioStreamController && f.audioTrackController), m = {
      levels: c,
      audioTracks: a,
      subtitleTracks: o,
      sessionData: t.sessionData,
      sessionKeys: t.sessionKeys,
      firstLevel: this._firstLevel,
      stats: t.stats,
      audio: n,
      video: s,
      altAudio: p && !u && a.some((g) => !!g.url)
    };
    this.hls.trigger(T.MANIFEST_PARSED, m);
  }
  get levels() {
    return this._levels.length === 0 ? null : this._levels;
  }
  get loadLevelObj() {
    return this.currentLevel;
  }
  get level() {
    return this.currentLevelIndex;
  }
  set level(e) {
    const t = this._levels;
    if (t.length === 0)
      return;
    if (e < 0 || e >= t.length) {
      const d = new Error("invalid level idx"), h = e < 0;
      if (this.hls.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.LEVEL_SWITCH_ERROR,
        level: e,
        fatal: h,
        error: d,
        reason: d.message
      }), h)
        return;
      e = Math.min(e, t.length - 1);
    }
    const i = this.currentLevelIndex, s = this.currentLevel, n = s ? s.attrs["PATHWAY-ID"] : void 0, a = t[e], o = a.attrs["PATHWAY-ID"];
    if (this.currentLevelIndex = e, this.currentLevel = a, i === e && s && n === o)
      return;
    this.log(`Switching to level ${e} (${a.height ? a.height + "p " : ""}${a.videoRange ? a.videoRange + " " : ""}${a.codecSet ? a.codecSet + " " : ""}@${a.bitrate})${o ? " with Pathway " + o : ""} from level ${i}${n ? " with Pathway " + n : ""}`);
    const c = {
      level: e,
      attrs: a.attrs,
      details: a.details,
      bitrate: a.bitrate,
      averageBitrate: a.averageBitrate,
      maxBitrate: a.maxBitrate,
      realBitrate: a.realBitrate,
      width: a.width,
      height: a.height,
      codecSet: a.codecSet,
      audioCodec: a.audioCodec,
      videoCodec: a.videoCodec,
      audioGroups: a.audioGroups,
      subtitleGroups: a.subtitleGroups,
      loaded: a.loaded,
      loadError: a.loadError,
      fragmentError: a.fragmentError,
      name: a.name,
      id: a.id,
      uri: a.uri,
      url: a.url,
      urlId: 0,
      audioGroupIds: a.audioGroupIds,
      textGroupIds: a.textGroupIds
    };
    this.hls.trigger(T.LEVEL_SWITCHING, c);
    const l = a.details;
    if (!l || l.live) {
      const d = this.switchParams(a.uri, s == null ? void 0 : s.details, l);
      this.loadPlaylist(d);
    }
  }
  get manualLevel() {
    return this.manualLevelIndex;
  }
  set manualLevel(e) {
    this.manualLevelIndex = e, this._startLevel === void 0 && (this._startLevel = e), e !== -1 && (this.level = e);
  }
  get firstLevel() {
    return this._firstLevel;
  }
  set firstLevel(e) {
    this._firstLevel = e;
  }
  get startLevel() {
    if (this._startLevel === void 0) {
      const e = this.hls.config.startLevel;
      return e !== void 0 ? e : this.hls.firstAutoLevel;
    }
    return this._startLevel;
  }
  set startLevel(e) {
    this._startLevel = e;
  }
  get pathways() {
    return this.steering ? this.steering.pathways() : [];
  }
  get pathwayPriority() {
    return this.steering ? this.steering.pathwayPriority : null;
  }
  set pathwayPriority(e) {
    if (this.steering) {
      const t = this.steering.pathways(), i = e.filter((s) => t.indexOf(s) !== -1);
      if (e.length < 1) {
        this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);
        return;
      }
      this.steering.pathwayPriority = i;
    }
  }
  onError(e, t) {
    t.fatal || !t.context || t.context.type === me.LEVEL && t.context.level === this.level && this.checkRetry(t);
  }
  // reset errors on the successful load of a fragment
  onFragBuffered(e, {
    frag: t
  }) {
    if (t !== void 0 && t.type === te.MAIN) {
      const i = t.elementaryStreams;
      if (!Object.keys(i).some((n) => !!i[n]))
        return;
      const s = this._levels[t.level];
      s != null && s.loadError && (this.log(`Resetting level error count of ${s.loadError} on frag buffered`), s.loadError = 0);
    }
  }
  onLevelLoaded(e, t) {
    var i;
    const {
      level: s,
      details: n
    } = t, a = t.levelInfo;
    if (!a) {
      var o;
      this.warn(`Invalid level index ${s}`), (o = t.deliveryDirectives) != null && o.skip && (n.deltaUpdateFailed = !0);
      return;
    }
    if (a === this.currentLevel || t.withoutMultiVariant) {
      a.fragmentError === 0 && (a.loadError = 0);
      let c = a.details;
      c === t.details && c.advanced && (c = void 0), this.playlistLoaded(s, t, c);
    } else (i = t.deliveryDirectives) != null && i.skip && (n.deltaUpdateFailed = !0);
  }
  loadPlaylist(e) {
    super.loadPlaylist(), this.shouldLoadPlaylist(this.currentLevel) && this.scheduleLoading(this.currentLevel, e);
  }
  loadingPlaylist(e, t) {
    super.loadingPlaylist(e, t);
    const i = this.getUrlWithDirectives(e.uri, t), s = this.currentLevelIndex, n = e.attrs["PATHWAY-ID"], a = e.details, o = a == null ? void 0 : a.age;
    this.log(`Loading level index ${s}${(t == null ? void 0 : t.msn) !== void 0 ? " at sn " + t.msn + " part " + t.part : ""}${n ? " Pathway " + n : ""}${o && a.live ? " age " + o.toFixed(1) + (a.type && " " + a.type || "") : ""} ${i}`), this.hls.trigger(T.LEVEL_LOADING, {
      url: i,
      level: s,
      levelInfo: e,
      pathwayId: e.attrs["PATHWAY-ID"],
      id: 0,
      // Deprecated Level urlId
      deliveryDirectives: t || null
    });
  }
  get nextLoadLevel() {
    return this.manualLevelIndex !== -1 ? this.manualLevelIndex : this.hls.nextAutoLevel;
  }
  set nextLoadLevel(e) {
    this.level = e, this.manualLevelIndex === -1 && (this.hls.nextAutoLevel = e);
  }
  removeLevel(e) {
    var t;
    if (this._levels.length === 1)
      return;
    const i = this._levels.filter((n, a) => a !== e ? !0 : (this.steering && this.steering.removeLevel(n), n === this.currentLevel && (this.currentLevel = null, this.currentLevelIndex = -1, n.details && n.details.fragments.forEach((o) => o.level = -1)), !1));
    m_(i), this._levels = i, this.currentLevelIndex > -1 && (t = this.currentLevel) != null && t.details && (this.currentLevelIndex = this.currentLevel.details.fragments[0].level), this.manualLevelIndex > -1 && (this.manualLevelIndex = this.currentLevelIndex);
    const s = i.length - 1;
    this._firstLevel = Math.min(this._firstLevel, s), this._startLevel && (this._startLevel = Math.min(this._startLevel, s)), this.hls.trigger(T.LEVELS_UPDATED, {
      levels: i
    });
  }
  onLevelsUpdated(e, {
    levels: t
  }) {
    this._levels = t;
  }
  checkMaxAutoUpdated() {
    const {
      autoLevelCapping: e,
      maxAutoLevel: t,
      maxHdcpLevel: i
    } = this.hls;
    this._maxAutoLevel !== t && (this._maxAutoLevel = t, this.hls.trigger(T.MAX_AUTO_LEVEL_UPDATED, {
      autoLevelCapping: e,
      levels: this.levels,
      maxAutoLevel: t,
      minAutoLevel: this.hls.minAutoLevel,
      maxHdcpLevel: i
    }));
  }
}
function rm(r) {
  const e = {};
  r.forEach((t) => {
    const i = t.groupId || "";
    t.id = e[i] = e[i] || 0, e[i]++;
  });
}
function dy() {
  return self.SourceBuffer || self.WebKitSourceBuffer;
}
function hy() {
  if (!ys())
    return !1;
  const e = dy();
  return !e || e.prototype && typeof e.prototype.appendBuffer == "function" && typeof e.prototype.remove == "function";
}
function v5() {
  if (!hy())
    return !1;
  const r = ys();
  return typeof (r == null ? void 0 : r.isTypeSupported) == "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((e) => r.isTypeSupported(vn(e, "video"))) || ["mp4a.40.2", "fLaC"].some((e) => r.isTypeSupported(vn(e, "audio"))));
}
function E5() {
  var r;
  const e = dy();
  return typeof (e == null || (r = e.prototype) == null ? void 0 : r.changeType) == "function";
}
const S5 = 100;
class T5 extends Yd {
  constructor(e, t, i) {
    super(e, t, i, "stream-controller", te.MAIN), this.audioCodecSwap = !1, this.level = -1, this._forceStartLoad = !1, this._hasEnoughToStart = !1, this.altAudio = 0, this.audioOnly = !1, this.fragPlaying = null, this.fragLastKbps = 0, this.couldBacktrack = !1, this.backtrackFragment = null, this.audioCodecSwitch = !1, this.videoBuffer = null, this.onMediaPlaying = () => {
      this.tick();
    }, this.onMediaSeeked = () => {
      const s = this.media, n = s ? s.currentTime : null;
      if (n === null || !q(n) || (this.log(`Media seeked to ${n.toFixed(3)}`), !this.getBufferedFrag(n)))
        return;
      const a = this.getFwdBufferInfoAtPos(s, n, te.MAIN, 0);
      if (a === null || a.len === 0) {
        this.warn(`Main forward buffer length at ${n} on "seeked" event ${a ? a.len : "empty"})`);
        return;
      }
      this.tick();
    }, this.registerListeners();
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls: e
    } = this;
    e.on(T.MANIFEST_PARSED, this.onManifestParsed, this), e.on(T.LEVEL_LOADING, this.onLevelLoading, this), e.on(T.LEVEL_LOADED, this.onLevelLoaded, this), e.on(T.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this), e.on(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.on(T.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this), e.on(T.BUFFER_CREATED, this.onBufferCreated, this), e.on(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.on(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.on(T.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  unregisterListeners() {
    super.unregisterListeners();
    const {
      hls: e
    } = this;
    e.off(T.MANIFEST_PARSED, this.onManifestParsed, this), e.off(T.LEVEL_LOADED, this.onLevelLoaded, this), e.off(T.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this), e.off(T.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), e.off(T.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this), e.off(T.BUFFER_CREATED, this.onBufferCreated, this), e.off(T.BUFFER_FLUSHED, this.onBufferFlushed, this), e.off(T.LEVELS_UPDATED, this.onLevelsUpdated, this), e.off(T.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  onHandlerDestroying() {
    this.onMediaPlaying = this.onMediaSeeked = null, this.unregisterListeners(), super.onHandlerDestroying();
  }
  startLoad(e, t) {
    if (this.levels) {
      const {
        lastCurrentTime: i,
        hls: s
      } = this;
      if (this.stopLoad(), this.setInterval(S5), this.level = -1, !this.startFragRequested) {
        let n = s.startLevel;
        n === -1 && (s.config.testBandwidth && this.levels.length > 1 ? (n = 0, this.bitrateTest = !0) : n = s.firstAutoLevel), s.nextLoadLevel = n, this.level = s.loadLevel, this._hasEnoughToStart = !!t;
      }
      i > 0 && e === -1 && !t && (this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`), e = i), this.state = K.IDLE, this.nextLoadPosition = this.lastCurrentTime = e + this.timelineOffset, this.startPosition = t ? -1 : e, this.tick();
    } else
      this._forceStartLoad = !0, this.state = K.STOPPED;
  }
  stopLoad() {
    this._forceStartLoad = !1, super.stopLoad();
  }
  doTick() {
    switch (this.state) {
      case K.WAITING_LEVEL: {
        const {
          levels: e,
          level: t
        } = this, i = e == null ? void 0 : e[t], s = i == null ? void 0 : i.details;
        if (s && (!s.live || this.levelLastLoaded === i && !this.waitForLive(i))) {
          if (this.waitForCdnTuneIn(s))
            break;
          this.state = K.IDLE;
          break;
        } else if (this.hls.nextLoadLevel !== this.level) {
          this.state = K.IDLE;
          break;
        }
        break;
      }
      case K.FRAG_LOADING_WAITING_RETRY:
        this.checkRetryDate();
        break;
    }
    this.state === K.IDLE && this.doTickIdle(), this.onTickEnd();
  }
  onTickEnd() {
    var e;
    super.onTickEnd(), (e = this.media) != null && e.readyState && this.media.seeking === !1 && (this.lastCurrentTime = this.media.currentTime), this.checkFragmentChanged();
  }
  doTickIdle() {
    const {
      hls: e,
      levelLastLoaded: t,
      levels: i,
      media: s
    } = this;
    if (t === null || !s && !this.primaryPrefetch && (this.startFragRequested || !e.config.startFragPrefetch) || this.altAudio && this.audioOnly)
      return;
    const n = this.buffering ? e.nextLoadLevel : e.loadLevel;
    if (!(i != null && i[n]))
      return;
    const a = i[n], o = this.getMainFwdBufferInfo();
    if (o === null)
      return;
    const c = this.getLevelDetails();
    if (c && this._streamEnded(o, c)) {
      const m = {};
      this.altAudio === 2 && (m.type = "video"), this.hls.trigger(T.BUFFER_EOS, m), this.state = K.ENDED;
      return;
    }
    if (!this.buffering)
      return;
    e.loadLevel !== n && e.manualLevel === -1 && this.log(`Adapting to level ${n} from level ${this.level}`), this.level = e.nextLoadLevel = n;
    const l = a.details;
    if (!l || this.state === K.WAITING_LEVEL || this.waitForLive(a)) {
      this.level = n, this.state = K.WAITING_LEVEL, this.startFragRequested = !1;
      return;
    }
    const d = o.len, h = this.getMaxBufferLength(a.maxBitrate);
    if (d >= h)
      return;
    this.backtrackFragment && this.backtrackFragment.start > o.end && (this.backtrackFragment = null);
    const u = this.backtrackFragment ? this.backtrackFragment.start : o.end;
    let f = this.getNextFragment(u, l);
    if (this.couldBacktrack && !this.fragPrevious && f && et(f) && this.fragmentTracker.getState(f) !== nt.OK) {
      var p;
      const g = ((p = this.backtrackFragment) != null ? p : f).sn - l.startSN, x = l.fragments[g - 1];
      x && f.cc === x.cc && (f = x, this.fragmentTracker.removeFragment(x));
    } else this.backtrackFragment && o.len && (this.backtrackFragment = null);
    if (f && this.isLoopLoading(f, u)) {
      if (!f.gap) {
        const g = this.audioOnly && !this.altAudio ? Oe.AUDIO : Oe.VIDEO, x = (g === Oe.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
        x && this.afterBufferFlushed(x, g, te.MAIN);
      }
      f = this.getNextFragmentLoopLoading(f, l, o, te.MAIN, h);
    }
    f && (f.initSegment && !f.initSegment.data && !this.bitrateTest && (f = f.initSegment), this.loadFragment(f, a, u));
  }
  loadFragment(e, t, i) {
    const s = this.fragmentTracker.getState(e);
    s === nt.NOT_LOADED || s === nt.PARTIAL ? et(e) ? this.bitrateTest ? (this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`), this._loadBitrateTestFrag(e, t)) : super.loadFragment(e, t, i) : this._loadInitSegment(e, t) : this.clearTrackerIfNeeded(e);
  }
  getBufferedFrag(e) {
    return this.fragmentTracker.getBufferedFrag(e, te.MAIN);
  }
  followingBufferedFrag(e) {
    return e ? this.getBufferedFrag(e.end + 0.5) : null;
  }
  /*
    on immediate level switch :
     - pause playback if playing
     - cancel any pending load request
     - and trigger a buffer flush
  */
  immediateLevelSwitch() {
    this.abortCurrentFrag(), this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  }
  /**
   * try to switch ASAP without breaking video playback:
   * in order to ensure smooth but quick level switching,
   * we need to find the next flushable buffer range
   * we should take into account new segment fetch time
   */
  nextLevelSwitch() {
    const {
      levels: e,
      media: t
    } = this;
    if (t != null && t.readyState) {
      let i;
      const s = this.getAppendedFrag(t.currentTime);
      s && s.start > 1 && this.flushMainBuffer(0, s.start - 1);
      const n = this.getLevelDetails();
      if (n != null && n.live) {
        const o = this.getMainFwdBufferInfo();
        if (!o || o.len < n.targetduration * 2)
          return;
      }
      if (!t.paused && e) {
        const o = this.hls.nextLoadLevel, c = e[o], l = this.fragLastKbps;
        l && this.fragCurrent ? i = this.fragCurrent.duration * c.maxBitrate / (1e3 * l) + 1 : i = 0;
      } else
        i = 0;
      const a = this.getBufferedFrag(t.currentTime + i);
      if (a) {
        const o = this.followingBufferedFrag(a);
        if (o) {
          this.abortCurrentFrag();
          const c = o.maxStartPTS ? o.maxStartPTS : o.start, l = o.duration, d = Math.max(a.end, c + Math.min(Math.max(l - this.config.maxFragLookUpTolerance, l * (this.couldBacktrack ? 0.5 : 0.125)), l * (this.couldBacktrack ? 0.75 : 0.25)));
          this.flushMainBuffer(d, Number.POSITIVE_INFINITY);
        }
      }
    }
  }
  abortCurrentFrag() {
    const e = this.fragCurrent;
    switch (this.fragCurrent = null, this.backtrackFragment = null, e && (e.abortRequests(), this.fragmentTracker.removeFragment(e)), this.state) {
      case K.KEY_LOADING:
      case K.FRAG_LOADING:
      case K.FRAG_LOADING_WAITING_RETRY:
      case K.PARSING:
      case K.PARSED:
        this.state = K.IDLE;
        break;
    }
    this.nextLoadPosition = this.getLoadPosition();
  }
  flushMainBuffer(e, t) {
    super.flushMainBuffer(e, t, this.altAudio === 2 ? "video" : null);
  }
  onMediaAttached(e, t) {
    super.onMediaAttached(e, t);
    const i = t.media;
    bt(i, "playing", this.onMediaPlaying), bt(i, "seeked", this.onMediaSeeked);
  }
  onMediaDetaching(e, t) {
    const {
      media: i
    } = this;
    i && (Ft(i, "playing", this.onMediaPlaying), Ft(i, "seeked", this.onMediaSeeked)), this.videoBuffer = null, this.fragPlaying = null, super.onMediaDetaching(e, t), !t.transferMedia && (this._hasEnoughToStart = !1);
  }
  onManifestLoading() {
    super.onManifestLoading(), this.log("Trigger BUFFER_RESET"), this.hls.trigger(T.BUFFER_RESET, void 0), this.couldBacktrack = !1, this.fragLastKbps = 0, this.fragPlaying = this.backtrackFragment = null, this.altAudio = 0, this.audioOnly = !1;
  }
  onManifestParsed(e, t) {
    let i = !1, s = !1;
    for (let n = 0; n < t.levels.length; n++) {
      const a = t.levels[n].audioCodec;
      a && (i = i || a.indexOf("mp4a.40.2") !== -1, s = s || a.indexOf("mp4a.40.5") !== -1);
    }
    this.audioCodecSwitch = i && s && !E5(), this.audioCodecSwitch && this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"), this.levels = t.levels, this.startFragRequested = !1;
  }
  onLevelLoading(e, t) {
    const {
      levels: i
    } = this;
    if (!i || this.state !== K.IDLE)
      return;
    const s = t.levelInfo;
    (!s.details || s.details.live && (this.levelLastLoaded !== s || s.details.expired) || this.waitForCdnTuneIn(s.details)) && (this.state = K.WAITING_LEVEL);
  }
  onLevelLoaded(e, t) {
    var i;
    const {
      levels: s,
      startFragRequested: n
    } = this, a = t.level, o = t.details, c = o.totalduration;
    if (!s) {
      this.warn(`Levels were reset while loading level ${a}`);
      return;
    }
    this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn ? `[part-${o.lastPartSn}-${o.lastPartIndex}]` : ""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);
    const l = t.levelInfo, d = this.fragCurrent;
    d && (this.state === K.FRAG_LOADING || this.state === K.FRAG_LOADING_WAITING_RETRY) && d.level !== t.level && d.loader && this.abortCurrentFrag();
    let h = 0;
    if (o.live || (i = l.details) != null && i.live) {
      var u;
      if (this.checkLiveUpdate(o), o.deltaUpdateFailed)
        return;
      h = this.alignPlaylists(o, l.details, (u = this.levelLastLoaded) == null ? void 0 : u.details);
    }
    if (l.details = o, this.levelLastLoaded = l, n || this.setStartPosition(o, h), this.hls.trigger(T.LEVEL_UPDATED, {
      details: o,
      level: a
    }), this.state === K.WAITING_LEVEL) {
      if (this.waitForCdnTuneIn(o))
        return;
      this.state = K.IDLE;
    }
    n && o.live && this.synchronizeToLiveEdge(o), this.tick();
  }
  synchronizeToLiveEdge(e) {
    const {
      config: t,
      media: i
    } = this;
    if (!i)
      return;
    const s = this.hls.liveSyncPosition, n = this.getLoadPosition(), a = e.fragmentStart, o = e.edge, c = n >= a - t.maxFragLookUpTolerance && n <= o;
    if (s !== null && i.duration > s && (n < s || !c)) {
      const d = t.liveMaxLatencyDuration !== void 0 ? t.liveMaxLatencyDuration : t.liveMaxLatencyDurationCount * e.targetduration;
      if ((!c && i.readyState < 4 || n < o - d) && (this._hasEnoughToStart || (this.nextLoadPosition = s), i.readyState))
        if (this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`), this.config.liveSyncMode === "buffered") {
          var l;
          const h = ce.bufferInfo(i, s, 0);
          if (!((l = h.buffered) != null && l.length)) {
            i.currentTime = s;
            return;
          }
          if (h.start <= n) {
            i.currentTime = s;
            return;
          }
          const {
            nextStart: f
          } = ce.bufferedInfo(h.buffered, n, 0);
          f && (i.currentTime = f);
        } else
          i.currentTime = s;
    }
  }
  _handleFragmentLoadProgress(e) {
    var t;
    const i = e.frag, {
      part: s,
      payload: n
    } = e, {
      levels: a
    } = this;
    if (!a) {
      this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);
      return;
    }
    const o = a[i.level];
    if (!o) {
      this.warn(`Level ${i.level} not found on progress`);
      return;
    }
    const c = o.details;
    if (!c) {
      this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`), this.fragmentTracker.removeFragment(i);
      return;
    }
    const l = o.videoCodec, d = c.PTSKnown || !c.live, h = (t = i.initSegment) == null ? void 0 : t.data, u = this._getAudioCodec(o), f = this.transmuxer = this.transmuxer || new O_(this.hls, te.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)), p = s ? s.index : -1, m = p !== -1, g = new $d(i.level, i.sn, i.stats.chunkCount, n.byteLength, p, m), x = this.initPTS[i.cc];
    f.push(n, h, u, l, i, s, c.totalduration, d, g, x);
  }
  onAudioTrackSwitching(e, t) {
    const i = this.hls, s = this.altAudio === 2;
    if (so(t.url, i))
      this.altAudio = 1;
    else {
      if (this.mediaBuffer !== this.media) {
        this.log("Switching on main audio, use media.buffered to schedule main fragment loading"), this.mediaBuffer = this.media;
        const a = this.fragCurrent;
        a && (this.log("Switching to main audio track, cancel main fragment load"), a.abortRequests(), this.fragmentTracker.removeFragment(a)), this.resetTransmuxer(), this.resetLoadingState();
      } else this.audioOnly && this.resetTransmuxer();
      if (s) {
        this.fragmentTracker.removeAllFragments(), i.once(T.BUFFER_FLUSHED, () => {
          this.hls && this.hls.trigger(T.AUDIO_TRACK_SWITCHED, t);
        }), i.trigger(T.BUFFER_FLUSHING, {
          startOffset: 0,
          endOffset: Number.POSITIVE_INFINITY,
          type: null
        });
        return;
      }
      i.trigger(T.AUDIO_TRACK_SWITCHED, t);
    }
  }
  onAudioTrackSwitched(e, t) {
    const i = so(t.url, this.hls);
    if (i) {
      const s = this.videoBuffer;
      s && this.mediaBuffer !== s && (this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"), this.mediaBuffer = s);
    }
    this.altAudio = i ? 2 : 0, this.tick();
  }
  onBufferCreated(e, t) {
    const i = t.tracks;
    let s, n, a = !1;
    for (const o in i) {
      const c = i[o];
      if (c.id === "main") {
        if (n = o, s = c, o === "video") {
          const l = i[o];
          l && (this.videoBuffer = l.buffer);
        }
      } else
        a = !0;
    }
    a && s ? (this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`), this.mediaBuffer = s.buffer) : this.mediaBuffer = this.media;
  }
  onFragBuffered(e, t) {
    const {
      frag: i,
      part: s
    } = t, n = i.type === te.MAIN;
    if (n) {
      if (this.fragContextChanged(i)) {
        this.warn(`Fragment ${i.sn}${s ? " p: " + s.index : ""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`), this.state === K.PARSED && (this.state = K.IDLE);
        return;
      }
      const o = s ? s.stats : i.stats;
      this.fragLastKbps = Math.round(8 * o.total / (o.buffering.end - o.loading.first)), et(i) && (this.fragPrevious = i), this.fragBufferedComplete(i, s);
    }
    const a = this.media;
    a && (!this._hasEnoughToStart && ce.getBuffered(a).length && (this._hasEnoughToStart = !0, this.seekToStartPos()), n && this.tick());
  }
  get hasEnoughToStart() {
    return this._hasEnoughToStart;
  }
  onError(e, t) {
    var i;
    if (t.fatal) {
      this.state = K.ERROR;
      return;
    }
    switch (t.details) {
      case V.FRAG_GAP:
      case V.FRAG_PARSING_ERROR:
      case V.FRAG_DECRYPT_ERROR:
      case V.FRAG_LOAD_ERROR:
      case V.FRAG_LOAD_TIMEOUT:
      case V.KEY_LOAD_ERROR:
      case V.KEY_LOAD_TIMEOUT:
        this.onFragmentOrKeyLoadError(te.MAIN, t);
        break;
      case V.LEVEL_LOAD_ERROR:
      case V.LEVEL_LOAD_TIMEOUT:
      case V.LEVEL_PARSING_ERROR:
        !t.levelRetry && this.state === K.WAITING_LEVEL && ((i = t.context) == null ? void 0 : i.type) === me.LEVEL && (this.state = K.IDLE);
        break;
      case V.BUFFER_ADD_CODEC_ERROR:
      case V.BUFFER_APPEND_ERROR:
        if (t.parent !== "main")
          return;
        this.reduceLengthAndFlushBuffer(t) && this.resetLoadingState();
        break;
      case V.BUFFER_FULL_ERROR:
        if (t.parent !== "main")
          return;
        this.reduceLengthAndFlushBuffer(t) && (!this.config.interstitialsController && this.config.assetPlayerId ? this._hasEnoughToStart = !0 : this.flushMainBuffer(0, Number.POSITIVE_INFINITY));
        break;
      case V.INTERNAL_EXCEPTION:
        this.recoverWorkerError(t);
        break;
    }
  }
  onFragLoadEmergencyAborted() {
    this.state = K.IDLE, this._hasEnoughToStart || (this.startFragRequested = !1, this.nextLoadPosition = this.lastCurrentTime), this.tickImmediate();
  }
  onBufferFlushed(e, {
    type: t
  }) {
    if (t !== Oe.AUDIO || !this.altAudio) {
      const i = (t === Oe.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
      i && (this.afterBufferFlushed(i, t, te.MAIN), this.tick());
    }
  }
  onLevelsUpdated(e, t) {
    this.level > -1 && this.fragCurrent && (this.level = this.fragCurrent.level, this.level === -1 && this.resetWhenMissingContext(this.fragCurrent)), this.levels = t.levels;
  }
  swapAudioCodec() {
    this.audioCodecSwap = !this.audioCodecSwap;
  }
  /**
   * Seeks to the set startPosition if not equal to the mediaElement's current time.
   */
  seekToStartPos() {
    const {
      media: e
    } = this;
    if (!e)
      return;
    const t = e.currentTime;
    let i = this.startPosition;
    if (i >= 0 && t < i) {
      if (e.seeking) {
        this.log(`could not seek to ${i}, already seeking at ${t}`);
        return;
      }
      const s = this.timelineOffset;
      s && i && (i += s);
      const n = this.getLevelDetails(), a = ce.getBuffered(e), o = a.length ? a.start(0) : 0, c = o - i, l = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
      (this.config.startOnSegmentBoundary || c > 0 && (c < l || this.loadingParts && c < 2 * ((n == null ? void 0 : n.partTarget) || 0))) && (this.log(`adjusting start position by ${c} to match buffer start`), i += c, this.startPosition = i), t < i && (this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`), e.currentTime = i);
    }
  }
  _getAudioCodec(e) {
    let t = this.config.defaultAudioCodec || e.audioCodec;
    return this.audioCodecSwap && t && (this.log("Swapping audio codec"), t.indexOf("mp4a.40.5") !== -1 ? t = "mp4a.40.2" : t = "mp4a.40.5"), t;
  }
  _loadBitrateTestFrag(e, t) {
    e.bitrateTest = !0, this._doFragLoad(e, t).then((i) => {
      const {
        hls: s
      } = this, n = i == null ? void 0 : i.frag;
      if (!n || this.fragContextChanged(n))
        return;
      t.fragmentError = 0, this.state = K.IDLE, this.startFragRequested = !1, this.bitrateTest = !1;
      const a = n.stats;
      a.parsing.start = a.parsing.end = a.buffering.start = a.buffering.end = self.performance.now(), s.trigger(T.FRAG_LOADED, i), n.bitrateTest = !1;
    }).catch((i) => {
      this.state === K.STOPPED || this.state === K.ERROR || (this.warn(i), this.resetFragmentLoading(e));
    });
  }
  _handleTransmuxComplete(e) {
    const t = this.playlistType, {
      hls: i
    } = this, {
      remuxResult: s,
      chunkMeta: n
    } = e, a = this.getCurrentContext(n);
    if (!a) {
      this.resetWhenMissingContext(n);
      return;
    }
    const {
      frag: o,
      part: c,
      level: l
    } = a, {
      video: d,
      text: h,
      id3: u,
      initSegment: f
    } = s, {
      details: p
    } = l, m = this.altAudio ? void 0 : s.audio;
    if (this.fragContextChanged(o)) {
      this.fragmentTracker.removeFragment(o);
      return;
    }
    if (this.state = K.PARSING, f) {
      const g = f.tracks;
      if (g) {
        const E = o.initSegment || o;
        if (this.unhandledEncryptionError(f, o))
          return;
        this._bufferInitSegment(l, g, E, n), i.trigger(T.FRAG_PARSING_INIT_SEGMENT, {
          frag: E,
          id: t,
          tracks: g
        });
      }
      const x = f.initPTS, _ = f.timescale, v = this.initPTS[o.cc];
      if (q(x) && (!v || v.baseTime !== x || v.timescale !== _)) {
        const E = f.trackId;
        this.initPTS[o.cc] = {
          baseTime: x,
          timescale: _,
          trackId: E
        }, i.trigger(T.INIT_PTS_FOUND, {
          frag: o,
          id: t,
          initPTS: x,
          timescale: _,
          trackId: E
        });
      }
    }
    if (d && p) {
      m && d.type === "audiovideo" && this.logMuxedErr(o);
      const g = p.fragments[o.sn - 1 - p.startSN], x = o.sn === p.startSN, _ = !g || o.cc > g.cc;
      if (s.independent !== !1) {
        const {
          startPTS: v,
          endPTS: E,
          startDTS: b,
          endDTS: A
        } = d;
        if (c)
          c.elementaryStreams[d.type] = {
            startPTS: v,
            endPTS: E,
            startDTS: b,
            endDTS: A
          };
        else if (d.firstKeyFrame && d.independent && n.id === 1 && !_ && (this.couldBacktrack = !0), d.dropped && d.independent) {
          const C = this.getMainFwdBufferInfo(), I = (C ? C.end : this.getLoadPosition()) + this.config.maxBufferHole, L = d.firstKeyFramePTS ? d.firstKeyFramePTS : v;
          if (!x && I < L - this.config.maxBufferHole && !_) {
            this.backtrack(o);
            return;
          } else _ && (o.gap = !0);
          o.setElementaryStreamInfo(d.type, o.start, E, o.start, A, !0);
        } else x && v - (p.appliedTimelineOffset || 0) > Fa && (o.gap = !0);
        o.setElementaryStreamInfo(d.type, v, E, b, A), this.backtrackFragment && (this.backtrackFragment = o), this.bufferFragmentData(d, o, c, n, x || _);
      } else if (x || _)
        o.gap = !0;
      else {
        this.backtrack(o);
        return;
      }
    }
    if (m) {
      const {
        startPTS: g,
        endPTS: x,
        startDTS: _,
        endDTS: v
      } = m;
      c && (c.elementaryStreams[Oe.AUDIO] = {
        startPTS: g,
        endPTS: x,
        startDTS: _,
        endDTS: v
      }), o.setElementaryStreamInfo(Oe.AUDIO, g, x, _, v), this.bufferFragmentData(m, o, c, n);
    }
    if (p && u != null && u.samples.length) {
      const g = {
        id: t,
        frag: o,
        details: p,
        samples: u.samples
      };
      i.trigger(T.FRAG_PARSING_METADATA, g);
    }
    if (p && h) {
      const g = {
        id: t,
        frag: o,
        details: p,
        samples: h.samples
      };
      i.trigger(T.FRAG_PARSING_USERDATA, g);
    }
  }
  logMuxedErr(e) {
    this.warn(`${et(e) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${e.url}`);
  }
  _bufferInitSegment(e, t, i, s) {
    if (this.state !== K.PARSING)
      return;
    this.audioOnly = !!t.audio && !t.video, this.altAudio && !this.audioOnly && (delete t.audio, t.audiovideo && this.logMuxedErr(i));
    const {
      audio: n,
      video: a,
      audiovideo: o
    } = t;
    if (n) {
      const l = e.audioCodec;
      let d = La(n.codec, l);
      d === "mp4a" && (d = "mp4a.40.5");
      const h = navigator.userAgent.toLowerCase();
      if (this.audioCodecSwitch) {
        d && (d.indexOf("mp4a.40.5") !== -1 ? d = "mp4a.40.2" : d = "mp4a.40.5");
        const u = n.metadata;
        u && "channelCount" in u && (u.channelCount || 1) !== 1 && h.indexOf("firefox") === -1 && (d = "mp4a.40.5");
      }
      d && d.indexOf("mp4a.40.5") !== -1 && h.indexOf("android") !== -1 && n.container !== "audio/mpeg" && (d = "mp4a.40.2", this.log(`Android: force audio codec to ${d}`)), l && l !== d && this.log(`Swapping manifest audio codec "${l}" for "${d}"`), n.levelCodec = d, n.id = te.MAIN, this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${d || ""}/${l || ""}/${n.codec}]`), delete t.audiovideo;
    }
    if (a) {
      a.levelCodec = e.videoCodec, a.id = te.MAIN;
      const l = a.codec;
      if ((l == null ? void 0 : l.length) === 4)
        switch (l) {
          case "hvc1":
          case "hev1":
            a.codec = "hvc1.1.6.L120.90";
            break;
          case "av01":
            a.codec = "av01.0.04M.08";
            break;
          case "avc1":
            a.codec = "avc1.42e01e";
            break;
        }
      this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec || ""}/${l}]${a.codec !== l ? " parsed-corrected=" + a.codec : ""}${a.supplemental ? " supplemental=" + a.supplemental : ""}`), delete t.audiovideo;
    }
    o && (this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`), delete t.video, delete t.audio);
    const c = Object.keys(t);
    if (c.length) {
      if (this.hls.trigger(T.BUFFER_CODECS, t), !this.hls)
        return;
      c.forEach((l) => {
        const h = t[l].initSegment;
        h != null && h.byteLength && this.hls.trigger(T.BUFFER_APPENDING, {
          type: l,
          data: h,
          frag: i,
          part: null,
          chunkMeta: s,
          parent: i.type
        });
      });
    }
    this.tickImmediate();
  }
  getMainFwdBufferInfo() {
    const e = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
    return this.getFwdBufferInfo(e, te.MAIN);
  }
  get maxBufferLength() {
    const {
      levels: e,
      level: t
    } = this, i = e == null ? void 0 : e[t];
    return i ? this.getMaxBufferLength(i.maxBitrate) : this.config.maxBufferLength;
  }
  backtrack(e) {
    this.couldBacktrack = !0, this.backtrackFragment = e, this.resetTransmuxer(), this.flushBufferGap(e), this.fragmentTracker.removeFragment(e), this.fragPrevious = null, this.nextLoadPosition = e.start, this.state = K.IDLE;
  }
  checkFragmentChanged() {
    const e = this.media;
    let t = null;
    if (e && e.readyState > 1 && e.seeking === !1) {
      const i = e.currentTime;
      if (ce.isBuffered(e, i) ? t = this.getAppendedFrag(i) : ce.isBuffered(e, i + 0.1) && (t = this.getAppendedFrag(i + 0.1)), t) {
        this.backtrackFragment = null;
        const s = this.fragPlaying, n = t.level;
        (!s || t.sn !== s.sn || s.level !== n) && (this.fragPlaying = t, this.hls.trigger(T.FRAG_CHANGED, {
          frag: t
        }), (!s || s.level !== n) && this.hls.trigger(T.LEVEL_SWITCHED, {
          level: n
        }));
      }
    }
  }
  get nextLevel() {
    const e = this.nextBufferedFrag;
    return e ? e.level : -1;
  }
  get currentFrag() {
    var e;
    if (this.fragPlaying)
      return this.fragPlaying;
    const t = ((e = this.media) == null ? void 0 : e.currentTime) || this.lastCurrentTime;
    return q(t) ? this.getAppendedFrag(t) : null;
  }
  get currentProgramDateTime() {
    var e;
    const t = ((e = this.media) == null ? void 0 : e.currentTime) || this.lastCurrentTime;
    if (q(t)) {
      const i = this.getLevelDetails(), s = this.currentFrag || (i ? Hs(null, i.fragments, t) : null);
      if (s) {
        const n = s.programDateTime;
        if (n !== null) {
          const a = n + (t - s.start) * 1e3;
          return new Date(a);
        }
      }
    }
    return null;
  }
  get currentLevel() {
    const e = this.currentFrag;
    return e ? e.level : -1;
  }
  get nextBufferedFrag() {
    const e = this.currentFrag;
    return e ? this.followingBufferedFrag(e) : null;
  }
  get forceStartLoad() {
    return this._forceStartLoad;
  }
}
class b5 extends qt {
  constructor(e, t) {
    super("key-loader", t), this.config = void 0, this.keyIdToKeyInfo = {}, this.emeController = null, this.config = e;
  }
  abort(e) {
    for (const i in this.keyIdToKeyInfo) {
      const s = this.keyIdToKeyInfo[i].loader;
      if (s) {
        var t;
        if (e && e !== ((t = s.context) == null ? void 0 : t.frag.type))
          return;
        s.abort();
      }
    }
  }
  detach() {
    for (const e in this.keyIdToKeyInfo) {
      const t = this.keyIdToKeyInfo[e];
      (t.mediaKeySessionContext || t.decryptdata.isCommonEncryption) && delete this.keyIdToKeyInfo[e];
    }
  }
  destroy() {
    this.detach();
    for (const e in this.keyIdToKeyInfo) {
      const t = this.keyIdToKeyInfo[e].loader;
      t && t.destroy();
    }
    this.keyIdToKeyInfo = {};
  }
  createKeyLoadError(e, t = V.KEY_LOAD_ERROR, i, s, n) {
    return new Zi({
      type: ie.NETWORK_ERROR,
      details: t,
      fatal: !1,
      frag: e,
      response: n,
      error: i,
      networkDetails: s
    });
  }
  loadClear(e, t, i) {
    if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
      if (t.length)
        for (let s = 0, n = t.length; s < n; s++) {
          const a = t[s];
          if (e.cc <= a.cc && (!et(e) || !et(a) || e.sn < a.sn) || !i && s == n - 1)
            return this.emeController.selectKeySystemFormat(a).then((o) => {
              if (!this.emeController)
                return;
              a.setKeyFormat(o);
              const c = Pa(o);
              if (c)
                return this.emeController.getKeySystemAccess([c]);
            });
        }
      if (this.config.requireKeySystemAccessOnStart) {
        const s = qr(this.config);
        if (s.length)
          return this.emeController.getKeySystemAccess(s);
      }
    }
    return null;
  }
  load(e) {
    return !e.decryptdata && e.encrypted && this.emeController && this.config.emeEnabled ? this.emeController.selectKeySystemFormat(e).then((t) => this.loadInternal(e, t)) : this.loadInternal(e);
  }
  loadInternal(e, t) {
    var i, s;
    t && e.setKeyFormat(t);
    const n = e.decryptdata;
    if (!n) {
      const d = new Error(t ? `Expected frag.decryptdata to be defined after setting format ${t}` : "Missing decryption data on fragment in onKeyLoading");
      return Promise.reject(this.createKeyLoadError(e, V.KEY_LOAD_ERROR, d));
    }
    const a = n.uri;
    if (!a)
      return Promise.reject(this.createKeyLoadError(e, V.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${a}"`)));
    const o = N0(n);
    let c = this.keyIdToKeyInfo[o];
    if ((i = c) != null && i.decryptdata.key)
      return n.key = c.decryptdata.key, Promise.resolve({
        frag: e,
        keyInfo: c
      });
    if ((s = c) != null && s.keyLoadPromise) {
      var l;
      switch ((l = c.mediaKeySessionContext) == null ? void 0 : l.keyStatus) {
        case "usable":
        case "usable-in-future":
          return c.keyLoadPromise.then((h) => {
            const {
              keyInfo: u
            } = h;
            return n.key = u.decryptdata.key, {
              frag: e,
              keyInfo: u
            };
          });
      }
    }
    switch (this.log(`Loading key ${Wt(n.keyId || [])} from ${e.type} ${e.level}`), c = this.keyIdToKeyInfo[o] = {
      decryptdata: n,
      keyLoadPromise: null,
      loader: null,
      mediaKeySessionContext: null
    }, n.method) {
      case "SAMPLE-AES":
      case "SAMPLE-AES-CENC":
      case "SAMPLE-AES-CTR":
        return n.keyFormat === "identity" ? this.loadKeyHTTP(c, e) : this.loadKeyEME(c, e);
      case "AES-128":
      case "AES-256":
      case "AES-256-CTR":
        return this.loadKeyHTTP(c, e);
      default:
        return Promise.reject(this.createKeyLoadError(e, V.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${n.method}"`)));
    }
  }
  loadKeyEME(e, t) {
    const i = {
      frag: t,
      keyInfo: e
    };
    if (this.emeController && this.config.emeEnabled) {
      const s = this.emeController.loadKey(i);
      return (e.keyLoadPromise = s.then((n) => (e.mediaKeySessionContext = n, i))).catch((n) => {
        throw e.keyLoadPromise = null, n.data && (n.data.frag = t), n;
      });
    }
    return Promise.resolve(i);
  }
  loadKeyHTTP(e, t) {
    const i = this.config, s = i.loader, n = new s(i);
    return t.keyLoader = e.loader = n, e.keyLoadPromise = new Promise((a, o) => {
      const c = {
        keyInfo: e,
        frag: t,
        responseType: "arraybuffer",
        url: e.decryptdata.uri
      }, l = i.keyLoadPolicy.default, d = {
        loadPolicy: l,
        timeout: l.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0
      }, h = {
        onSuccess: (u, f, p, m) => {
          const {
            frag: g,
            keyInfo: x,
            url: _
          } = p, v = N0(x.decryptdata) || _;
          if (!g.decryptdata || x !== this.keyIdToKeyInfo[v])
            return o(this.createKeyLoadError(g, V.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), m));
          x.decryptdata.key = g.decryptdata.key = new Uint8Array(u.data), g.keyLoader = null, x.loader = null, a({
            frag: g,
            keyInfo: x
          });
        },
        onError: (u, f, p, m) => {
          this.resetLoader(f), o(this.createKeyLoadError(t, V.KEY_LOAD_ERROR, new Error(`HTTP Error ${u.code} loading key ${u.text}`), p, we({
            url: c.url,
            data: void 0
          }, u)));
        },
        onTimeout: (u, f, p) => {
          this.resetLoader(f), o(this.createKeyLoadError(t, V.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), p));
        },
        onAbort: (u, f, p) => {
          this.resetLoader(f), o(this.createKeyLoadError(t, V.INTERNAL_ABORTED, new Error("key loading aborted"), p));
        }
      };
      n.load(c, d, h);
    });
  }
  resetLoader(e) {
    const {
      frag: t,
      keyInfo: i,
      url: s
    } = e, n = i.loader;
    t.keyLoader === n && (t.keyLoader = null, i.loader = null);
    const a = N0(i.decryptdata) || s;
    delete this.keyIdToKeyInfo[a], n && n.destroy();
  }
}
function N0(r) {
  const e = r.keyId;
  return e ? Wt(e) : r.uri;
}
function nm(r) {
  const {
    type: e
  } = r;
  switch (e) {
    case me.AUDIO_TRACK:
      return te.AUDIO;
    case me.SUBTITLE_TRACK:
      return te.SUBTITLE;
    default:
      return te.MAIN;
  }
}
function G0(r, e) {
  let t = r.url;
  return (t === void 0 || t.indexOf("data:") === 0) && (t = e.url), t;
}
class A5 {
  constructor(e) {
    this.hls = void 0, this.loaders = /* @__PURE__ */ Object.create(null), this.variableList = null, this.onManifestLoaded = this.checkAutostartLoad, this.hls = e, this.registerListeners();
  }
  startLoad(e) {
  }
  stopLoad() {
    this.destroyInternalLoaders();
  }
  registerListeners() {
    const {
      hls: e
    } = this;
    e.on(T.MANIFEST_LOADING, this.onManifestLoading, this), e.on(T.LEVEL_LOADING, this.onLevelLoading, this), e.on(T.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this), e.on(T.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this), e.on(T.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  unregisterListeners() {
    const {
      hls: e
    } = this;
    e.off(T.MANIFEST_LOADING, this.onManifestLoading, this), e.off(T.LEVEL_LOADING, this.onLevelLoading, this), e.off(T.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this), e.off(T.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this), e.off(T.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  /**
   * Returns defaults or configured loader-type overloads (pLoader and loader config params)
   */
  createInternalLoader(e) {
    const t = this.hls.config, i = t.pLoader, s = t.loader, n = i || s, a = new n(t);
    return this.loaders[e.type] = a, a;
  }
  getInternalLoader(e) {
    return this.loaders[e.type];
  }
  resetInternalLoader(e) {
    this.loaders[e] && delete this.loaders[e];
  }
  /**
   * Call `destroy` on all internal loader instances mapped (one per context type)
   */
  destroyInternalLoaders() {
    for (const e in this.loaders) {
      const t = this.loaders[e];
      t && t.destroy(), this.resetInternalLoader(e);
    }
  }
  destroy() {
    this.variableList = null, this.unregisterListeners(), this.destroyInternalLoaders();
  }
  onManifestLoading(e, t) {
    const {
      url: i
    } = t;
    this.variableList = null, this.load({
      id: null,
      level: 0,
      responseType: "text",
      type: me.MANIFEST,
      url: i,
      deliveryDirectives: null,
      levelOrTrack: null
    });
  }
  onLevelLoading(e, t) {
    const {
      id: i,
      level: s,
      pathwayId: n,
      url: a,
      deliveryDirectives: o,
      levelInfo: c
    } = t;
    this.load({
      id: i,
      level: s,
      pathwayId: n,
      responseType: "text",
      type: me.LEVEL,
      url: a,
      deliveryDirectives: o,
      levelOrTrack: c
    });
  }
  onAudioTrackLoading(e, t) {
    const {
      id: i,
      groupId: s,
      url: n,
      deliveryDirectives: a,
      track: o
    } = t;
    this.load({
      id: i,
      groupId: s,
      level: null,
      responseType: "text",
      type: me.AUDIO_TRACK,
      url: n,
      deliveryDirectives: a,
      levelOrTrack: o
    });
  }
  onSubtitleTrackLoading(e, t) {
    const {
      id: i,
      groupId: s,
      url: n,
      deliveryDirectives: a,
      track: o
    } = t;
    this.load({
      id: i,
      groupId: s,
      level: null,
      responseType: "text",
      type: me.SUBTITLE_TRACK,
      url: n,
      deliveryDirectives: a,
      levelOrTrack: o
    });
  }
  onLevelsUpdated(e, t) {
    const i = this.loaders[me.LEVEL];
    if (i) {
      const s = i.context;
      s && !t.levels.some((n) => n === s.levelOrTrack) && (i.abort(), delete this.loaders[me.LEVEL]);
    }
  }
  load(e) {
    var t;
    const i = this.hls.config;
    let s = this.getInternalLoader(e);
    if (s) {
      const l = this.hls.logger, d = s.context;
      if (d && d.levelOrTrack === e.levelOrTrack && (d.url === e.url || d.deliveryDirectives && !e.deliveryDirectives)) {
        d.url === e.url ? l.log(`[playlist-loader]: ignore ${e.url} ongoing request`) : l.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);
        return;
      }
      l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`), s.abort();
    }
    let n;
    if (e.type === me.MANIFEST ? n = i.manifestLoadPolicy.default : n = Me({}, i.playlistLoadPolicy.default, {
      timeoutRetry: null,
      errorRetry: null
    }), s = this.createInternalLoader(e), q((t = e.deliveryDirectives) == null ? void 0 : t.part)) {
      let l;
      if (e.type === me.LEVEL && e.level !== null ? l = this.hls.levels[e.level].details : e.type === me.AUDIO_TRACK && e.id !== null ? l = this.hls.audioTracks[e.id].details : e.type === me.SUBTITLE_TRACK && e.id !== null && (l = this.hls.subtitleTracks[e.id].details), l) {
        const d = l.partTarget, h = l.targetduration;
        if (d && h) {
          const u = Math.max(d * 3, h * 0.8) * 1e3;
          n = Me({}, n, {
            maxTimeToFirstByteMs: Math.min(u, n.maxTimeToFirstByteMs),
            maxLoadTimeMs: Math.min(u, n.maxTimeToFirstByteMs)
          });
        }
      }
    }
    const a = n.errorRetry || n.timeoutRetry || {}, o = {
      loadPolicy: n,
      timeout: n.maxLoadTimeMs,
      maxRetry: a.maxNumRetry || 0,
      retryDelay: a.retryDelayMs || 0,
      maxRetryDelay: a.maxRetryDelayMs || 0
    }, c = {
      onSuccess: (l, d, h, u) => {
        const f = this.getInternalLoader(h);
        this.resetInternalLoader(h.type);
        const p = l.data;
        if (p.indexOf("#EXTM3U") !== 0) {
          this.handleManifestParsingError(l, h, new Error("no EXTM3U delimiter"), u || null, d);
          return;
        }
        d.parsing.start = performance.now(), Pi.isMediaPlaylist(p) || h.type !== me.MANIFEST ? this.handleTrackOrLevelPlaylist(l, d, h, u || null, f) : this.handleMasterPlaylist(l, d, h, u);
      },
      onError: (l, d, h, u) => {
        this.handleNetworkError(d, h, !1, l, u);
      },
      onTimeout: (l, d, h) => {
        this.handleNetworkError(d, h, !0, void 0, l);
      }
    };
    s.load(e, o, c);
  }
  checkAutostartLoad() {
    if (!this.hls)
      return;
    const {
      config: {
        autoStartLoad: e,
        startPosition: t
      },
      forceStartLoad: i
    } = this.hls;
    (e || i) && (this.hls.logger.log(`${e ? "auto" : "force"} startLoad with configured startPosition ${t}`), this.hls.startLoad(t));
  }
  handleMasterPlaylist(e, t, i, s) {
    const n = this.hls, a = e.data, o = G0(e, i), c = Pi.parseMasterPlaylist(a, o);
    if (c.playlistParsingError) {
      this.handleManifestParsingError(e, i, c.playlistParsingError, s, t);
      return;
    }
    const {
      contentSteering: l,
      levels: d,
      sessionData: h,
      sessionKeys: u,
      startTimeOffset: f,
      variableList: p
    } = c;
    this.variableList = p;
    const {
      AUDIO: m = [],
      SUBTITLES: g,
      "CLOSED-CAPTIONS": x
    } = Pi.parseMasterPlaylistMedia(a, o, c);
    m.length && !m.some((v) => !v.url) && d[0].audioCodec && !d[0].attrs.AUDIO && (this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"), m.unshift({
      type: "main",
      name: "main",
      groupId: "main",
      default: !1,
      autoselect: !1,
      forced: !1,
      id: -1,
      attrs: new $e({}),
      bitrate: 0,
      url: ""
    })), n.trigger(T.MANIFEST_LOADED, {
      levels: d,
      audioTracks: m,
      subtitles: g,
      captions: x,
      contentSteering: l,
      url: o,
      stats: t,
      networkDetails: s,
      sessionData: h,
      sessionKeys: u,
      startTimeOffset: f,
      variableList: p
    });
  }
  handleTrackOrLevelPlaylist(e, t, i, s, n) {
    const a = this.hls, {
      id: o,
      level: c,
      type: l
    } = i, d = G0(e, i), h = q(c) ? c : q(o) ? o : 0, u = nm(i), f = Pi.parseLevelPlaylist(e.data, d, h, u, 0, this.variableList);
    if (l === me.MANIFEST) {
      const p = {
        attrs: new $e({}),
        bitrate: 0,
        details: f,
        name: "",
        url: d
      };
      f.requestScheduled = t.loading.start + u_(f, 0), a.trigger(T.MANIFEST_LOADED, {
        levels: [p],
        audioTracks: [],
        url: d,
        stats: t,
        networkDetails: s,
        sessionData: null,
        sessionKeys: null,
        contentSteering: null,
        startTimeOffset: null,
        variableList: null
      });
    }
    t.parsing.end = performance.now(), i.levelDetails = f, this.handlePlaylistLoaded(f, e, t, i, s, n);
  }
  handleManifestParsingError(e, t, i, s, n) {
    this.hls.trigger(T.ERROR, {
      type: ie.NETWORK_ERROR,
      details: V.MANIFEST_PARSING_ERROR,
      fatal: t.type === me.MANIFEST,
      url: e.url,
      err: i,
      error: i,
      reason: i.message,
      response: e,
      context: t,
      networkDetails: s,
      stats: n
    });
  }
  handleNetworkError(e, t, i = !1, s, n) {
    let a = `A network ${i ? "timeout" : "error" + (s ? " (status " + s.code + ")" : "")} occurred while loading ${e.type}`;
    e.type === me.LEVEL ? a += `: ${e.level} id: ${e.id}` : (e.type === me.AUDIO_TRACK || e.type === me.SUBTITLE_TRACK) && (a += ` id: ${e.id} group-id: "${e.groupId}"`);
    const o = new Error(a);
    this.hls.logger.warn(`[playlist-loader]: ${a}`);
    let c = V.UNKNOWN, l = !1;
    const d = this.getInternalLoader(e);
    switch (e.type) {
      case me.MANIFEST:
        c = i ? V.MANIFEST_LOAD_TIMEOUT : V.MANIFEST_LOAD_ERROR, l = !0;
        break;
      case me.LEVEL:
        c = i ? V.LEVEL_LOAD_TIMEOUT : V.LEVEL_LOAD_ERROR, l = !1;
        break;
      case me.AUDIO_TRACK:
        c = i ? V.AUDIO_TRACK_LOAD_TIMEOUT : V.AUDIO_TRACK_LOAD_ERROR, l = !1;
        break;
      case me.SUBTITLE_TRACK:
        c = i ? V.SUBTITLE_TRACK_LOAD_TIMEOUT : V.SUBTITLE_LOAD_ERROR, l = !1;
        break;
    }
    d && this.resetInternalLoader(e.type);
    const h = {
      type: ie.NETWORK_ERROR,
      details: c,
      fatal: l,
      url: e.url,
      loader: d,
      context: e,
      error: o,
      networkDetails: t,
      stats: n
    };
    if (s) {
      const u = (t == null ? void 0 : t.url) || e.url;
      h.response = we({
        url: u,
        data: void 0
      }, s);
    }
    this.hls.trigger(T.ERROR, h);
  }
  handlePlaylistLoaded(e, t, i, s, n, a) {
    const o = this.hls, {
      type: c,
      level: l,
      id: d,
      groupId: h,
      deliveryDirectives: u
    } = s, f = G0(t, s), p = nm(s), m = typeof s.level == "number" && p === te.MAIN ? l : void 0;
    if (!e.fragments.length) {
      const x = e.playlistParsingError = new Error("No Segments found in Playlist");
      o.trigger(T.ERROR, {
        type: ie.NETWORK_ERROR,
        details: V.LEVEL_EMPTY_ERROR,
        fatal: !1,
        url: f,
        error: x,
        reason: x.message,
        response: t,
        context: s,
        level: m,
        parent: p,
        networkDetails: n,
        stats: i
      });
      return;
    }
    e.targetduration || (e.playlistParsingError = new Error("Missing Target Duration"));
    const g = e.playlistParsingError;
    if (g) {
      if (this.hls.logger.warn(`${g} ${e.url}`), !o.config.ignorePlaylistParsingErrors) {
        o.trigger(T.ERROR, {
          type: ie.NETWORK_ERROR,
          details: V.LEVEL_PARSING_ERROR,
          fatal: !1,
          url: f,
          error: g,
          reason: g.message,
          response: t,
          context: s,
          level: m,
          parent: p,
          networkDetails: n,
          stats: i
        });
        return;
      }
      e.playlistParsingError = null;
    }
    switch (e.live && a && (a.getCacheAge && (e.ageHeader = a.getCacheAge() || 0), (!a.getCacheAge || isNaN(e.ageHeader)) && (e.ageHeader = 0)), c) {
      case me.MANIFEST:
      case me.LEVEL:
        o.trigger(T.LEVEL_LOADED, {
          details: e,
          levelInfo: s.levelOrTrack || o.levels[0],
          level: m || 0,
          id: d || 0,
          stats: i,
          networkDetails: n,
          deliveryDirectives: u,
          withoutMultiVariant: c === me.MANIFEST
        });
        break;
      case me.AUDIO_TRACK:
        o.trigger(T.AUDIO_TRACK_LOADED, {
          details: e,
          track: s.levelOrTrack,
          id: d || 0,
          groupId: h || "",
          stats: i,
          networkDetails: n,
          deliveryDirectives: u
        });
        break;
      case me.SUBTITLE_TRACK:
        o.trigger(T.SUBTITLE_TRACK_LOADED, {
          details: e,
          track: s.levelOrTrack,
          id: d || 0,
          groupId: h || "",
          stats: i,
          networkDetails: n,
          deliveryDirectives: u
        });
        break;
    }
  }
}
class Xi {
  /**
   * Get the video-dev/hls.js package version.
   */
  static get version() {
    return Sn;
  }
  /**
   * Check if the required MediaSource Extensions are available.
   */
  static isMSESupported() {
    return hy();
  }
  /**
   * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
   */
  static isSupported() {
    return v5();
  }
  /**
   * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
   */
  static getMediaSource() {
    return ys();
  }
  static get Events() {
    return T;
  }
  static get MetadataSchema() {
    return Ht;
  }
  static get ErrorTypes() {
    return ie;
  }
  static get ErrorDetails() {
    return V;
  }
  /**
   * Get the default configuration applied to new instances.
   */
  static get DefaultConfig() {
    return Xi.defaultConfig ? Xi.defaultConfig : l5;
  }
  /**
   * Replace the default configuration applied to new instances.
   */
  static set DefaultConfig(e) {
    Xi.defaultConfig = e;
  }
  /**
   * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
   * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
   */
  constructor(e = {}) {
    this.config = void 0, this.userConfig = void 0, this.logger = void 0, this.coreComponents = void 0, this.networkControllers = void 0, this._emitter = new zd(), this._autoLevelCapping = -1, this._maxHdcpLevel = null, this.abrController = void 0, this.bufferController = void 0, this.capLevelController = void 0, this.latencyController = void 0, this.levelController = void 0, this.streamController = void 0, this.audioStreamController = void 0, this.subtititleStreamController = void 0, this.audioTrackController = void 0, this.subtitleTrackController = void 0, this.interstitialsController = void 0, this.gapController = void 0, this.emeController = void 0, this.cmcdController = void 0, this._media = null, this._url = null, this._sessionId = void 0, this.triggeringException = void 0, this.started = !1;
    const t = this.logger = w4(e.debug || !1, "Hls instance", e.assetPlayerId), i = this.config = d5(Xi.DefaultConfig, e, t);
    this.userConfig = e, i.progressive && h5(i, t);
    const {
      abrController: s,
      bufferController: n,
      capLevelController: a,
      errorController: o,
      fpsController: c
    } = i, l = new o(this), d = this.abrController = new s(this), h = new AC(this), u = i.interstitialsController, f = u ? this.interstitialsController = new u(this, Xi) : null, p = this.bufferController = new n(this, h), m = this.capLevelController = new a(this), g = new c(this), x = new A5(this), _ = i.contentSteeringController, v = _ ? new _(this) : null, E = this.levelController = new x5(this, v), b = new _5(this), A = new b5(this.config, this.logger), C = this.streamController = new T5(this, h, A), I = this.gapController = new m5(this, h);
    m.setStreamController(C), g.setStreamController(C);
    const L = [x, E, C];
    f && L.splice(1, 0, f), v && L.splice(1, 0, v), this.networkControllers = L;
    const R = [d, p, I, m, g, b, h];
    this.audioTrackController = this.createController(i.audioTrackController, L);
    const D = i.audioStreamController;
    D && L.push(this.audioStreamController = new D(this, h, A)), this.subtitleTrackController = this.createController(i.subtitleTrackController, L);
    const M = i.subtitleStreamController;
    M && L.push(this.subtititleStreamController = new M(this, h, A)), this.createController(i.timelineController, R), A.emeController = this.emeController = this.createController(i.emeController, R), this.cmcdController = this.createController(i.cmcdController, R), this.latencyController = this.createController(y5, R), this.coreComponents = R, L.push(l);
    const w = l.onErrorOut;
    typeof w == "function" && this.on(T.ERROR, w, l), this.on(T.MANIFEST_LOADED, x.onManifestLoaded, x);
  }
  createController(e, t) {
    if (e) {
      const i = new e(this);
      return t && t.push(i), i;
    }
    return null;
  }
  // Delegate the EventEmitter through the public API of Hls.js
  on(e, t, i = this) {
    this._emitter.on(e, t, i);
  }
  once(e, t, i = this) {
    this._emitter.once(e, t, i);
  }
  removeAllListeners(e) {
    this._emitter.removeAllListeners(e);
  }
  off(e, t, i = this, s) {
    this._emitter.off(e, t, i, s);
  }
  listeners(e) {
    return this._emitter.listeners(e);
  }
  emit(e, t, i) {
    return this._emitter.emit(e, t, i);
  }
  trigger(e, t) {
    if (this.config.debug)
      return this.emit(e, e, t);
    try {
      return this.emit(e, e, t);
    } catch (i) {
      if (this.logger.error("An internal error happened while handling event " + e + '. Error message: "' + i.message + '". Here is a stacktrace:', i), !this.triggeringException) {
        this.triggeringException = !0;
        const s = e === T.ERROR;
        this.trigger(T.ERROR, {
          type: ie.OTHER_ERROR,
          details: V.INTERNAL_EXCEPTION,
          fatal: s,
          event: e,
          error: i
        }), this.triggeringException = !1;
      }
    }
    return !1;
  }
  listenerCount(e) {
    return this._emitter.listenerCount(e);
  }
  /**
   * Dispose of the instance
   */
  destroy() {
    this.logger.log("destroy"), this.trigger(T.DESTROYING, void 0), this.detachMedia(), this.removeAllListeners(), this._autoLevelCapping = -1, this._url = null, this.networkControllers.forEach((t) => t.destroy()), this.networkControllers.length = 0, this.coreComponents.forEach((t) => t.destroy()), this.coreComponents.length = 0;
    const e = this.config;
    e.xhrSetup = e.fetchSetup = void 0, this.userConfig = null;
  }
  /**
   * Attaches Hls.js to a media element
   */
  attachMedia(e) {
    if (!e || "media" in e && !e.media) {
      const n = new Error(`attachMedia failed: invalid argument (${e})`);
      this.trigger(T.ERROR, {
        type: ie.OTHER_ERROR,
        details: V.ATTACH_MEDIA_ERROR,
        fatal: !0,
        error: n
      });
      return;
    }
    this.logger.log("attachMedia"), this._media && (this.logger.warn("media must be detached before attaching"), this.detachMedia());
    const t = "media" in e, i = t ? e.media : e, s = t ? e : {
      media: i
    };
    this._media = i, this.trigger(T.MEDIA_ATTACHING, s);
  }
  /**
   * Detach Hls.js from the media
   */
  detachMedia() {
    this.logger.log("detachMedia"), this.trigger(T.MEDIA_DETACHING, {}), this._media = null;
  }
  /**
   * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
   */
  transferMedia() {
    this._media = null;
    const e = this.bufferController.transferMedia();
    return this.trigger(T.MEDIA_DETACHING, {
      transferMedia: e
    }), e;
  }
  /**
   * Set the source URL. Can be relative or absolute.
   */
  loadSource(e) {
    this.stopLoad();
    const t = this.media, i = this._url, s = this._url = Nd.buildAbsoluteURL(self.location.href, e, {
      alwaysNormalize: !0
    });
    this._autoLevelCapping = -1, this._maxHdcpLevel = null, this.logger.log(`loadSource:${s}`), t && i && (i !== s || this.bufferController.hasSourceTypes()) && (this.detachMedia(), this.attachMedia(t)), this.trigger(T.MANIFEST_LOADING, {
      url: e
    });
  }
  /**
   * Gets the currently loaded URL
   */
  get url() {
    return this._url;
  }
  /**
   * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
   */
  get hasEnoughToStart() {
    return this.streamController.hasEnoughToStart;
  }
  /**
   * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
   */
  get startPosition() {
    return this.streamController.startPositionValue;
  }
  /**
   * Start loading data from the stream source.
   * Depending on default config, client starts loading automatically when a source is set.
   *
   * @param startPosition - Set the start position to stream from.
   * Defaults to -1 (None: starts from earliest point)
   */
  startLoad(e = -1, t) {
    this.logger.log(`startLoad(${e + (t ? ", <skip seek to start>" : "")})`), this.started = !0, this.resumeBuffering();
    for (let i = 0; i < this.networkControllers.length && (this.networkControllers[i].startLoad(e, t), !(!this.started || !this.networkControllers)); i++)
      ;
  }
  /**
   * Stop loading of any stream data.
   */
  stopLoad() {
    this.logger.log("stopLoad"), this.started = !1;
    for (let e = 0; e < this.networkControllers.length && (this.networkControllers[e].stopLoad(), !(this.started || !this.networkControllers)); e++)
      ;
  }
  /**
   * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
   */
  get loadingEnabled() {
    return this.started;
  }
  /**
   * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
   */
  get bufferingEnabled() {
    return this.streamController.bufferingEnabled;
  }
  /**
   * Resumes stream controller segment loading after `pauseBuffering` has been called.
   */
  resumeBuffering() {
    this.bufferingEnabled || (this.logger.log("resume buffering"), this.networkControllers.forEach((e) => {
      e.resumeBuffering && e.resumeBuffering();
    }));
  }
  /**
   * Prevents stream controller from loading new segments until `resumeBuffering` is called.
   * This allows for media buffering to be paused without interupting playlist loading.
   */
  pauseBuffering() {
    this.bufferingEnabled && (this.logger.log("pause buffering"), this.networkControllers.forEach((e) => {
      e.pauseBuffering && e.pauseBuffering();
    }));
  }
  get inFlightFragments() {
    const e = {
      [te.MAIN]: this.streamController.inFlightFrag
    };
    return this.audioStreamController && (e[te.AUDIO] = this.audioStreamController.inFlightFrag), this.subtititleStreamController && (e[te.SUBTITLE] = this.subtititleStreamController.inFlightFrag), e;
  }
  /**
   * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
   */
  swapAudioCodec() {
    this.logger.log("swapAudioCodec"), this.streamController.swapAudioCodec();
  }
  /**
   * When the media-element fails, this allows to detach and then re-attach it
   * as one call (convenience method).
   *
   * Automatic recovery of media-errors by this process is configurable.
   */
  recoverMediaError() {
    this.logger.log("recoverMediaError");
    const e = this._media, t = e == null ? void 0 : e.currentTime;
    this.detachMedia(), e && (this.attachMedia(e), t && this.startLoad(t));
  }
  removeLevel(e) {
    this.levelController.removeLevel(e);
  }
  /**
   * @returns a UUID for this player instance
   */
  get sessionId() {
    let e = this._sessionId;
    return e || (e = this._sessionId = mI()), e;
  }
  /**
   * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
   */
  get levels() {
    const e = this.levelController.levels;
    return e || [];
  }
  /**
   * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
   */
  get latestLevelDetails() {
    return this.streamController.getLevelDetails() || null;
  }
  /**
   * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
   */
  get loadLevelObj() {
    return this.levelController.loadLevelObj;
  }
  /**
   * Index of quality level (variant) currently played
   */
  get currentLevel() {
    return this.streamController.currentLevel;
  }
  /**
   * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.
   */
  set currentLevel(e) {
    this.logger.log(`set currentLevel:${e}`), this.levelController.manualLevel = e, this.streamController.immediateLevelSwitch();
  }
  /**
   * Index of next quality level loaded as scheduled by stream controller.
   */
  get nextLevel() {
    return this.streamController.nextLevel;
  }
  /**
   * Set quality level index for next loaded data.
   * This will switch the video quality asap, without interrupting playback.
   * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
   * @param newLevel - Pass -1 for automatic level selection
   */
  set nextLevel(e) {
    this.logger.log(`set nextLevel:${e}`), this.levelController.manualLevel = e, this.streamController.nextLevelSwitch();
  }
  /**
   * Return the quality level of the currently or last (of none is loaded currently) segment
   */
  get loadLevel() {
    return this.levelController.level;
  }
  /**
   * Set quality level index for next loaded data in a conservative way.
   * This will switch the quality without flushing, but interrupt current loading.
   * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
   * @param newLevel - Pass -1 for automatic level selection
   */
  set loadLevel(e) {
    this.logger.log(`set loadLevel:${e}`), this.levelController.manualLevel = e;
  }
  /**
   * get next quality level loaded
   */
  get nextLoadLevel() {
    return this.levelController.nextLoadLevel;
  }
  /**
   * Set quality level of next loaded segment in a fully "non-destructive" way.
   * Same as `loadLevel` but will wait for next switch (until current loading is done).
   */
  set nextLoadLevel(e) {
    this.levelController.nextLoadLevel = e;
  }
  /**
   * Return "first level": like a default level, if not set,
   * falls back to index of first level referenced in manifest
   */
  get firstLevel() {
    return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  }
  /**
   * Sets "first-level", see getter.
   */
  set firstLevel(e) {
    this.logger.log(`set firstLevel:${e}`), this.levelController.firstLevel = e;
  }
  /**
   * Return the desired start level for the first fragment that will be loaded.
   * The default value of -1 indicates automatic start level selection.
   * Setting hls.nextAutoLevel without setting a startLevel will result in
   * the nextAutoLevel value being used for one fragment load.
   */
  get startLevel() {
    const e = this.levelController.startLevel;
    return e === -1 && this.abrController.forcedAutoLevel > -1 ? this.abrController.forcedAutoLevel : e;
  }
  /**
   * set  start level (level of first fragment that will be played back)
   * if not overrided by user, first level appearing in manifest will be used as start level
   * if -1 : automatic start level selection, playback will start from level matching download bandwidth
   * (determined from download of first segment)
   */
  set startLevel(e) {
    this.logger.log(`set startLevel:${e}`), e !== -1 && (e = Math.max(e, this.minAutoLevel)), this.levelController.startLevel = e;
  }
  /**
   * Whether level capping is enabled.
   * Default value is set via `config.capLevelToPlayerSize`.
   */
  get capLevelToPlayerSize() {
    return this.config.capLevelToPlayerSize;
  }
  /**
   * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
   */
  set capLevelToPlayerSize(e) {
    const t = !!e;
    t !== this.config.capLevelToPlayerSize && (t ? this.capLevelController.startCapping() : (this.capLevelController.stopCapping(), this.autoLevelCapping = -1, this.streamController.nextLevelSwitch()), this.config.capLevelToPlayerSize = t);
  }
  /**
   * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
   */
  get autoLevelCapping() {
    return this._autoLevelCapping;
  }
  /**
   * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
   */
  get bandwidthEstimate() {
    const {
      bwEstimator: e
    } = this.abrController;
    return e ? e.getEstimate() : NaN;
  }
  set bandwidthEstimate(e) {
    this.abrController.resetEstimator(e);
  }
  get abrEwmaDefaultEstimate() {
    const {
      bwEstimator: e
    } = this.abrController;
    return e ? e.defaultEstimate : NaN;
  }
  /**
   * get time to first byte estimate
   * @type {number}
   */
  get ttfbEstimate() {
    const {
      bwEstimator: e
    } = this.abrController;
    return e ? e.getEstimateTTFB() : NaN;
  }
  /**
   * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
   */
  set autoLevelCapping(e) {
    this._autoLevelCapping !== e && (this.logger.log(`set autoLevelCapping:${e}`), this._autoLevelCapping = e, this.levelController.checkMaxAutoUpdated());
  }
  get maxHdcpLevel() {
    return this._maxHdcpLevel;
  }
  set maxHdcpLevel(e) {
    cC(e) && this._maxHdcpLevel !== e && (this._maxHdcpLevel = e, this.levelController.checkMaxAutoUpdated());
  }
  /**
   * True when automatic level selection enabled
   */
  get autoLevelEnabled() {
    return this.levelController.manualLevel === -1;
  }
  /**
   * Level set manually (if any)
   */
  get manualLevel() {
    return this.levelController.manualLevel;
  }
  /**
   * min level selectable in auto mode according to config.minAutoBitrate
   */
  get minAutoLevel() {
    const {
      levels: e,
      config: {
        minAutoBitrate: t
      }
    } = this;
    if (!e) return 0;
    const i = e.length;
    for (let s = 0; s < i; s++)
      if (e[s].maxBitrate >= t)
        return s;
    return 0;
  }
  /**
   * max level selectable in auto mode according to autoLevelCapping
   */
  get maxAutoLevel() {
    const {
      levels: e,
      autoLevelCapping: t,
      maxHdcpLevel: i
    } = this;
    let s;
    if (t === -1 && e != null && e.length ? s = e.length - 1 : s = t, i)
      for (let n = s; n--; ) {
        const a = e[n].attrs["HDCP-LEVEL"];
        if (a && a <= i)
          return n;
      }
    return s;
  }
  get firstAutoLevel() {
    return this.abrController.firstAutoLevel;
  }
  /**
   * next automatically selected quality level
   */
  get nextAutoLevel() {
    return this.abrController.nextAutoLevel;
  }
  /**
   * this setter is used to force next auto level.
   * this is useful to force a switch down in auto mode:
   * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
   * forced value is valid for one fragment. upon successful frag loading at forced level,
   * this value will be resetted to -1 by ABR controller.
   */
  set nextAutoLevel(e) {
    this.abrController.nextAutoLevel = e;
  }
  /**
   * get the datetime value relative to media.currentTime for the active level Program Date Time if present
   */
  get playingDate() {
    return this.streamController.currentProgramDateTime;
  }
  get mainForwardBufferInfo() {
    return this.streamController.getMainFwdBufferInfo();
  }
  get maxBufferLength() {
    return this.streamController.maxBufferLength;
  }
  /**
   * Find and select the best matching audio track, making a level switch when a Group change is necessary.
   * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
   */
  setAudioOption(e) {
    var t;
    return ((t = this.audioTrackController) == null ? void 0 : t.setAudioOption(e)) || null;
  }
  /**
   * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
   * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
   */
  setSubtitleOption(e) {
    var t;
    return ((t = this.subtitleTrackController) == null ? void 0 : t.setSubtitleOption(e)) || null;
  }
  /**
   * Get the complete list of audio tracks across all media groups
   */
  get allAudioTracks() {
    const e = this.audioTrackController;
    return e ? e.allAudioTracks : [];
  }
  /**
   * Get the list of selectable audio tracks
   */
  get audioTracks() {
    const e = this.audioTrackController;
    return e ? e.audioTracks : [];
  }
  /**
   * index of the selected audio track (index in audio track lists)
   */
  get audioTrack() {
    const e = this.audioTrackController;
    return e ? e.audioTrack : -1;
  }
  /**
   * selects an audio track, based on its index in audio track lists
   */
  set audioTrack(e) {
    const t = this.audioTrackController;
    t && (t.audioTrack = e);
  }
  /**
   * get the complete list of subtitle tracks across all media groups
   */
  get allSubtitleTracks() {
    const e = this.subtitleTrackController;
    return e ? e.allSubtitleTracks : [];
  }
  /**
   * get alternate subtitle tracks list from playlist
   */
  get subtitleTracks() {
    const e = this.subtitleTrackController;
    return e ? e.subtitleTracks : [];
  }
  /**
   * index of the selected subtitle track (index in subtitle track lists)
   */
  get subtitleTrack() {
    const e = this.subtitleTrackController;
    return e ? e.subtitleTrack : -1;
  }
  get media() {
    return this._media;
  }
  /**
   * select an subtitle track, based on its index in subtitle track lists
   */
  set subtitleTrack(e) {
    const t = this.subtitleTrackController;
    t && (t.subtitleTrack = e);
  }
  /**
   * Whether subtitle display is enabled or not
   */
  get subtitleDisplay() {
    const e = this.subtitleTrackController;
    return e ? e.subtitleDisplay : !1;
  }
  /**
   * Enable/disable subtitle display rendering
   */
  set subtitleDisplay(e) {
    const t = this.subtitleTrackController;
    t && (t.subtitleDisplay = e);
  }
  /**
   * get mode for Low-Latency HLS loading
   */
  get lowLatencyMode() {
    return this.config.lowLatencyMode;
  }
  /**
   * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
   */
  set lowLatencyMode(e) {
    this.config.lowLatencyMode = e;
  }
  /**
   * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
   * @returns null prior to loading live Playlist
   */
  get liveSyncPosition() {
    return this.latencyController.liveSyncPosition;
  }
  /**
   * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
   * @returns 0 before first playlist is loaded
   */
  get latency() {
    return this.latencyController.latency;
  }
  /**
   * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
   * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
   * @returns 0 before first playlist is loaded
   */
  get maxLatency() {
    return this.latencyController.maxLatency;
  }
  /**
   * target distance from the edge as calculated by the latency controller
   */
  get targetLatency() {
    return this.latencyController.targetLatency;
  }
  set targetLatency(e) {
    this.latencyController.targetLatency = e;
  }
  /**
   * the rate at which the edge of the current live playlist is advancing or 1 if there is none
   */
  get drift() {
    return this.latencyController.drift;
  }
  /**
   * set to true when startLoad is called before MANIFEST_PARSED event
   */
  get forceStartLoad() {
    return this.streamController.forceStartLoad;
  }
  /**
   * ContentSteering pathways getter
   */
  get pathways() {
    return this.levelController.pathways;
  }
  /**
   * ContentSteering pathwayPriority getter/setter
   */
  get pathwayPriority() {
    return this.levelController.pathwayPriority;
  }
  set pathwayPriority(e) {
    this.levelController.pathwayPriority = e;
  }
  /**
   * returns true when all SourceBuffers are buffered to the end
   */
  get bufferedToEnd() {
    var e;
    return !!((e = this.bufferController) != null && e.bufferedToEnd);
  }
  /**
   * returns Interstitials Program Manager
   */
  get interstitialsManager() {
    var e;
    return ((e = this.interstitialsController) == null ? void 0 : e.interstitialsManager) || null;
  }
  /**
   * returns mediaCapabilities.decodingInfo for a variant/rendition
   */
  getMediaDecodingInfo(e, t = this.allAudioTracks) {
    const i = t_(t);
    return qg(e, i, navigator.mediaCapabilities);
  }
}
Xi.defaultConfig = void 0;
const C5 = ye;
class am {
  constructor(e, t, i) {
    y(this, "type", "HlsPlayer");
    y(this, "TAG", this.type);
    y(this, "mediaDataSource");
    y(this, "config");
    y(this, "mediaElement", null);
    y(this, "pendingSeekTime");
    y(this, "statisticsReporterInterval");
    y(this, "retryPlayCnt", 0);
    y(this, "emitter", new ve());
    y(this, "hlsPlayer");
    y(this, "containerElement", null);
    y(this, "playerDeviceInfo");
    y(this, "onvLoadedMetadata", () => {
      this.pendingSeekTime != null && (this.mediaElement && (this.mediaElement.currentTime = this.pendingSeekTime), this.pendingSeekTime = void 0), this.proxyEmit(z.MEDIA_INFO, this.mediaInfo);
    });
    y(this, "onvCanPlay", () => {
      this.proxyEmit(z.CAN_PLAY);
    });
    y(this, "onvEnded", () => {
      this.proxyEmit(z.PLAY_ENDED);
    });
    y(this, "onvError", (e) => {
      var i;
      let t = (i = this.mediaElement) == null ? void 0 : i.error;
      if (this.retryPlayCnt = this.retryPlayCnt || 0, !t && this.retryPlayCnt < 3) {
        this.play(), this.retryPlayCnt++;
        return;
      }
      this.proxyEmit(z.ERROR, "MEDIA_ERROR", e, t || {});
    });
    y(this, "onvPlaying", () => {
      this.proxyEmit(z.PLAYING);
    });
    y(this, "onvTimeupdate", () => {
      const e = Math.round(this.currentTime * 1e3);
      this.proxyEmit(z.TIME_UPDATE, e, e), this.paused || this.onvPlaying();
    });
    this.playerDeviceInfo = i, this.config = Pr(), typeof t == "object" && Object.assign(this.config, t), this.mediaDataSource = e, this.initMediaElement();
  }
  seek(e) {
    S.w(this.TAG, "seek " + e);
  }
  seekTo(e) {
    this.playHls(e);
  }
  static setLogger(e, t) {
    S.setLogger(e), We.applyConfig(t);
  }
  async getVodUrl(e) {
    const { iotId: t = "" } = this.playerDeviceInfo || {}, i = {
      iotId: t,
      beginTime: e.beginTime,
      endTime: e.endTime ?? e.beginTime + 5 * 60 * 1e3
    };
    return (await w1(i)).vodUrl;
  }
  initMediaElement() {
    S.i(this.TAG, "initMediaElement");
    const { hasAudio: e, muted: t, videoWrapper: i } = this.config, s = e || t ? "muted" : "", n = "player-type";
    let a = this.mediaElement = i.querySelector("video");
    a || (i.innerHTML = `<video autoplay
            webkit-playsinline="true" x-webkit-airplay="true" x5-playsinline="true" 
            playsInline ${s} 
            class="${Xs}-player-video-element">
            Your browser is too old which doesn't support HTML5 video.
        </video>`, a = this.mediaElement = i.querySelector("video")), a && (a.setAttribute(n, this.type), a.style.display = "block", this.attachMediaElement(a));
  }
  destroy() {
    var e;
    this.hlsPlayer ? this.hlsPlayer.destroy() : this.mediaElement && ((e = this.containerElement) == null || e.removeChild(this.mediaElement)), this.mediaElement && (this.unload(), this.detachMediaElement()), this.emitter.removeAllListeners();
  }
  on(e, t) {
    const i = this.mediaElement;
    e === z.MEDIA_INFO ? i && i.readyState !== 0 && Promise.resolve().then(() => {
      this.proxyEmit(z.MEDIA_INFO, this.mediaInfo);
    }) : e === z.STATISTICS_INFO && i && i.readyState !== 0 && Promise.resolve().then(() => {
      this.proxyEmit(z.STATISTICS_INFO, this.statisticsInfo);
    }), this.emitter.addListener(e, t);
  }
  off(e, t) {
    this.emitter.removeListener(e, t);
  }
  attachMediaElement(e) {
    if (e.addEventListener("loadedmetadata", this.onvLoadedMetadata), e.addEventListener("canplay", this.onvCanPlay), e.addEventListener("ended", this.onvEnded), e.addEventListener("error", this.onvError), e.addEventListener("playing", this.onvPlaying), e.addEventListener("timeupdate", this.onvTimeupdate), this.pendingSeekTime != null)
      try {
        e.currentTime = this.pendingSeekTime, this.pendingSeekTime = void 0;
      } catch {
      }
  }
  detachMediaElement() {
    let e = this.mediaElement;
    e && (e.src = "", e.removeAttribute("src"), e.removeEventListener("loadedmetadata", this.onvLoadedMetadata), e.removeEventListener("canplay", this.onvCanPlay), e.removeEventListener("ended", this.onvEnded), e.removeEventListener("error", this.onvError), e.removeEventListener("playing", this.onvPlaying), e.removeEventListener("timeupdate", this.onvTimeupdate), e = this.mediaElement = null), this.statisticsReporterInterval != null && (self.clearInterval(this.statisticsReporterInterval), this.statisticsReporterInterval = void 0);
  }
  load() {
    var i;
    if (!this.mediaElement)
      throw new qe("HTMLMediaElement must be attached before load()!");
    const t = (i = this.playerDeviceInfo) == null ? void 0 : i.seekParam;
    t ? this.playHls(t) : this.mediaDataSource.url && this.playUrl(this.mediaDataSource.url), this.statisticsReporterInterval = self.setInterval(this.reportStatisticsInfo.bind(this), this.config.statisticsInfoReportInterval);
  }
  unload() {
    S.i(this.TAG, "hls unload");
    const e = this.mediaElement;
    e && (e.pause(), e.srcObject = null, e.src = "", e.removeAttribute("src"), e.load()), this.statisticsReporterInterval != null && (self.clearInterval(this.statisticsReporterInterval), this.statisticsReporterInterval = void 0);
  }
  play() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.play()) ?? Promise.resolve();
  }
  pause() {
    var e;
    ((e = this.mediaElement) == null ? void 0 : e.pause()) ?? Promise.resolve();
  }
  get paused() {
    var e;
    return (e = this.mediaElement) == null ? void 0 : e.paused;
  }
  get videoRender() {
    return this.mediaElement;
  }
  get audioRender() {
    return this.mediaElement;
  }
  get buffered() {
    var e;
    return (e = this.mediaElement) == null ? void 0 : e.buffered;
  }
  get duration() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.duration) ?? 0;
  }
  get volume() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.volume) ?? 0;
  }
  set volume(e) {
    this.mediaElement && (this.mediaElement.volume = e);
  }
  get muted() {
    var e;
    return ((e = this.mediaElement) == null ? void 0 : e.muted) ?? !1;
  }
  set muted(e) {
    this.mediaElement && (this.mediaElement.muted = e);
  }
  get currentTime() {
    return this.mediaElement ? this.mediaElement.currentTime : 0;
  }
  set currentTime(e) {
    this.mediaElement ? this.mediaElement.currentTime = e : this.pendingSeekTime = e;
  }
  get mediaInfo() {
    const e = this.mediaElement;
    let i = {
      mimeType: (e instanceof HTMLAudioElement ? "audio/" : "video/") + this.mediaDataSource.type,
      duration: 0,
      width: 0,
      height: 0
    };
    return e && (i.duration = Math.floor(e.duration * 1e3), e instanceof HTMLVideoElement && (i.width = e.videoWidth, i.height = e.videoHeight)), i;
  }
  get statisticsInfo() {
    let e = {
      playerType: this.type,
      url: this.mediaDataSource.url,
      decodedFrames: 0,
      droppedFrames: 0
    };
    const t = this.mediaElement;
    if (!(t instanceof HTMLVideoElement))
      return e;
    let i = !0, s = 0, n = 0;
    const { webkitDecodedFrameCount: a, webkitDroppedFrameCount: o } = t;
    if (t.getVideoPlaybackQuality) {
      let c = t.getVideoPlaybackQuality();
      s = c.totalVideoFrames, n = c.droppedVideoFrames;
    } else a != null ? (s = a, n = o) : i = !1;
    return i && (e.decodedFrames = s, e.droppedFrames = n), e;
  }
  get metaData() {
    if (this.mediaElement) {
      const { videoWidth: e = 0, videoHeight: t = 0 } = this.mediaElement || {};
      return {
        video: {
          codec: _g(de.H265),
          codecType: de.H265,
          codecWidth: e,
          codecHeight: t
        }
      };
    }
  }
  set playbackRate(e) {
    this.mediaElement && (this.mediaElement.playbackRate = e);
  }
  proxyEmit(e, ...t) {
    var i;
    (i = this.emitter) == null || i.emit(e, ...t);
  }
  reportStatisticsInfo() {
    this.proxyEmit(z.STATISTICS_INFO, this.statisticsInfo);
  }
  createHlsPlayer() {
    var e;
    if ((e = this.hlsPlayer) == null || e.destroy(), !(je.getFeatureList().nativeHLS && C5.mobile)) if (Xi.isSupported())
      this.hlsPlayer = new Xi({
        debug: this.config.debug,
        enableWorker: !0,
        lowLatencyMode: !0,
        backBufferLength: 90
      }), this.hlsPlayer.attachMedia(this.mediaElement);
    else
      throw new qe("unsupport hls!");
  }
  playHls(e) {
    this.getVodUrl(e).then((t) => {
      this.playUrl(t);
    }).catch((t) => this.proxyEmit(z.ERROR, t));
  }
  playUrl(e) {
    var t;
    this.createHlsPlayer(), this.hlsPlayer ? (t = this.hlsPlayer) == null || t.loadSource(e) : this.mediaElement && (this.mediaElement.src = e, this.mediaElement.load());
  }
}
class Po {
  constructor(e) {
    y(this, "player");
    this.player = e;
  }
  supportMethod(e) {
    const t = this.methodList.includes(e);
    return t || S.e(this.TAG, `plugin ${this.pluginName} unsupport method:${e}`), t;
  }
  getMetaData() {
    var e;
    return (e = this.player) == null ? void 0 : e.getMediaMeta();
  }
  destroy() {
    this.player = void 0;
  }
}
const R5 = ye, Mr = R5.mobile, om = Mr ? "touchstart" : "mousedown", lm = Mr ? "touchmove" : "mousemove", cm = Mr ? "touchend" : "mouseup", dm = Mr ? "touchcancel" : "mouseleave", Xc = [0, 90, 180, 270], Yc = 5, zc = 1;
class I5 {
  constructor(e) {
    y(this, "zoomElement", null);
    y(this, "cssCursor");
    y(this, "domWidth", 0);
    y(this, "domHeight", 0);
    y(this, "lastPoint");
    y(this, "scale", 1);
    y(this, "tx", 0);
    y(this, "ty", 0);
    y(this, "rotate", 0);
    y(this, "moveOutTimer", -1);
    y(this, "canMoving", !1);
    y(this, "onMouseDown", (e) => {
      e.preventDefault();
      let t = this, i;
      Mr ? i = e.touches[0] : i = e, t.lastPoint = {
        x: i.screenX,
        y: i.screenY
      }, t.canMoving = !0;
    });
    y(this, "onMouseMove", (e) => {
      const t = this, i = t.scale, s = t.lastPoint;
      if (!t.canMoving || i === 1 || !s) return;
      let n;
      Mr ? n = e.touches[0] : n = e;
      const a = n.screenX, o = n.screenY, c = a - s.x, l = o - s.y;
      this.translateXY(c, l), clearTimeout(t.moveOutTimer), t.moveOutTimer = setTimeout(() => {
        t.canMoving = !1;
      }, 500), t.lastPoint = { x: a, y: o };
    });
    y(this, "onMouseUp", () => {
      let e = this;
      e.canMoving = !1, e.lastPoint = void 0;
    });
    let t = this, i = typeof e == "string" ? document.querySelector(e) : e;
    if (!i) throw "lost zoom element!";
    t.zoomElement = i, this.cssCursor = "default", t.domWidth = i.offsetWidth, t.domHeight = i.offsetHeight;
    let { scale: s = 1, tx: n = 0, ty: a = 0, rotate: o = 0 } = i.dataset;
    t.scale = +s, t.tx = +n, t.ty = +a, t.rotate = +o, t.addListener(i);
  }
  destroy() {
    let e = this, t = e.zoomElement;
    t != null && (e.removeListener(t), t = e.zoomElement = null);
  }
  removeListener(e) {
    const t = this;
    e.removeEventListener(om, t.onMouseDown), e.removeEventListener(lm, t.onMouseMove), e.removeEventListener(cm, t.onMouseUp), e.removeEventListener(dm, t.onMouseUp);
  }
  addListener(e) {
    const t = this;
    e.addEventListener(om, t.onMouseDown, !1), e.addEventListener(lm, t.onMouseMove, {
      passive: !1
      //  禁止 passive 效果
    }), e.addEventListener(cm, t.onMouseUp, !1), e.addEventListener(dm, t.onMouseUp, !1);
  }
  translateXY(e, t) {
    const i = this, s = i.scale, n = e / (i.domWidth * s), a = t / (i.domHeight * s), o = i.tx, c = i.ty;
    let l = o + n, d = c + a, h = (s - 1) / 2 / s;
    e > 0 ? l > h && (l = h) : l < -1 * h && (l = -1 * h), t > 0 ? d > h && (d = h) : d < -1 * h && (d = -1 * h), !(o === l && c === d) && (i.tx = l, i.ty = d, i.updateStyle(s, l, d));
  }
  /**
   * 设置缩放比率
   * @param scaleRate
   * @returns
   */
  setScale(e) {
    let t = this, i = t.scale, s = t.tx, n = t.ty;
    if (e < zc || e > Yc || e === i) return;
    if (e < i) {
      let o = (e - 1) / 2 / e;
      s > o ? s = o : s < -1 * o && (s = -1 * o), n > o ? n = o : n < -1 * o && (n = -1 * o), t.tx = s, t.ty = n;
    }
    t.scale = i = e;
    const a = e !== 1 ? "move" : "default";
    a !== this.cssCursor && t.zoomElement && (t.zoomElement.style.cursor = this.cssCursor = a), this.updateStyle(i, s, n);
  }
  setRotate(e) {
    if (!Xc.includes(e)) return;
    this.rotate = e;
    const t = this.zoomElement;
    if (!t) return;
    t.setAttribute("data-rotate", e.toString());
    const i = t.querySelector("." + Fm);
    if (i) {
      let s = `rotate3d(0, 0, 1, ${e}deg)`;
      if (e == 90 || e == 270) {
        const n = this.domHeight / this.domWidth;
        s = `${s} scale(${n},${n})`;
      }
      this.setDomTransform(i, s);
    }
  }
  updateStyle(e, t, i) {
    let s = "", n = this.zoomElement;
    if (!n) return;
    const a = n.style;
    (t !== 0 || i !== 0) && (s = `translate(${t * 100}%,${i * 100}%)`), n.setAttribute("data-zoom", e.toString()), n.setAttribute("data-tx", t.toString()), n.setAttribute("data-ty", i.toString()), e > 1 && (s = `scale(${e},${e}) ${s}`), this.setDomTransform(n, s);
    let o = Math.floor(Math.random() * 255), c = Math.floor(Math.random() * 255), l = Math.floor(Math.random() * 255);
    a.backgroundColor = `rgba(${o},${c},${l},0)`;
  }
  setDomTransform(e, t) {
    ["", "ms", "webkit", "o", "moz"].forEach((i) => {
      e.style[i ? i + "Transform" : "transform"] = t;
    });
  }
  getZoomInfo() {
    const e = this;
    return {
      scale: e.scale,
      tx: e.tx,
      ty: e.ty,
      rotate: e.rotate
    };
  }
}
var hn = ((r) => (r[r.setScale = Xa.setScale] = "setScale", r[r.setRotate = Xa.setRotate] = "setRotate", r.getZoomInfo = "getZoomInfo", r))(hn || {});
class L5 extends Po {
  constructor(t) {
    var s;
    super(t);
    y(this, "methodList", Object.values(hn));
    y(this, "pluginName", Li.ZoomPlug);
    y(this, "TAG");
    y(this, "zoomer");
    this.TAG = S.traceTag(this.pluginName, t.getTraceId());
    const i = (s = t.getRootElement()) == null ? void 0 : s.querySelector("." + fa);
    i && (this.zoomer = new I5(i));
  }
  /**
   * 设置缩放比例
   * @param scaleRate
   */
  setScale(t) {
    var i;
    if (zc > t || Yc < t) {
      S.w(this.TAG, `call setScale ${t} must in [${zc},${Yc}]`);
      return;
    }
    S.d(this.TAG, `call setScale zoom=${t}`), (i = this.zoomer) == null || i.setScale(t);
  }
  /**
   * 设置缩放比例
   * @param scaleRate
   */
  setRotate(t) {
    var i;
    if (!Xc.includes(t)) {
      S.w(this.TAG, `deg=${t} not in ${Xc.join(",")}`);
      return;
    }
    S.d(this.TAG, `call setRotate zoom=${t}`), (i = this.zoomer) == null || i.setRotate(t);
  }
  getZoomInfo() {
    var t;
    return S.d(this.TAG, "call getZoomInfo"), (t = this.zoomer) == null ? void 0 : t.getZoomInfo();
  }
  destroy() {
    var t;
    super.destroy(), (t = this.zoomer) == null || t.destroy();
  }
  async callMethod(t, ...i) {
    if (this.supportMethod(t))
      switch (t) {
        case "getZoomInfo":
          return this.getZoomInfo();
        case hn.setRotate:
          return this.setRotate(i[0]);
        case hn.setScale:
          this.setScale(i[0]);
          break;
      }
  }
}
var Oa = ((r) => (r.snapshotHide = "snapshotHide", r[r.snapshot = Ya.snapshot] = "snapshot", r[r.snapshotZoom = Ya.snapshotZoom] = "snapshotZoom", r))(Oa || {});
class D5 extends Po {
  constructor(t) {
    super(t);
    y(this, "methodList", Object.values(Oa));
    y(this, "TAG");
    y(this, "pluginName", Li.SnapshotPlugin);
    y(this, "snapshotCanvas");
    y(this, "bufferCanvas");
    y(this, "vw", 0);
    y(this, "vh", 0);
    this.TAG = S.traceTag(this.pluginName, t.getTraceId()), this.snapshotCanvas = document.createElement("canvas"), this.bufferCanvas = document.createElement("canvas");
    const i = t.getRootElement();
    if (i) {
      const s = i.parentNode;
      this.vw = s.offsetWidth, this.vh = s.offsetHeight;
    }
  }
  async callMethod(t, ...i) {
    let s;
    switch (t) {
      case "snapshotHide":
        this.snapshot(
          0
          /* HIDDEN */
        );
        break;
      case Oa.snapshot:
        s = this.snapshot(
          1
          /* ORIGIN */
        );
        break;
      case Oa.snapshotZoom:
        s = this.snapshot(
          2
          /* ZOOM */
        );
        break;
    }
    return s;
  }
  getCanvas() {
    return this.snapshotCanvas;
  }
  /**
   * 截图
   * @param {*} snapshotType - 截图类型
   * @returns
   */
  async snapshot(t) {
    var Y, W, k;
    const i = (Y = this.player) == null ? void 0 : Y.getMediaMeta(), s = (W = this.player) == null ? void 0 : W.getVideoRender();
    if (!s) return;
    const n = this.snapshotCanvas, a = this.bufferCanvas;
    if (!n || !a) return;
    const o = 1;
    let { codecWidth: c, codecHeight: l } = (i == null ? void 0 : i.video) || {};
    const d = s;
    if (d instanceof HTMLCanvasElement) {
      const { width: P, height: B } = d;
      c = P, l = B;
    }
    if (d instanceof HTMLVideoElement) {
      const { videoWidth: P, videoHeight: B } = d;
      P && B && (c = P, l = B);
    }
    if (!c || !l) return;
    if (t === 0) {
      n.style.visibility = "hidden";
      return;
    }
    n.style.visibility = "visible";
    const h = Math.min(1280 / c, 1), u = c * o;
    a.width = u, a.height = l;
    let f = a.getContext("2d", { alpha: !1 });
    [s].forEach((P, B) => {
      f == null || f.drawImage(P, c * B, 0);
    });
    const p = this.vw, m = this.vh;
    let g = 0, x = 0, _ = p, v = m;
    if (t === 2) {
      const P = (k = this.player) == null ? void 0 : k.getPlugin(Li.ZoomPlug);
      if (P) {
        let { rotate: B, scale: O, tx: j, ty: Q } = await P.callMethod(hn.getZoomInfo) || {};
        if (S.d(this.TAG, `snapshot type=${t} zoom info scale=${O} tx=${j} ty=${Q}`), O = Number(O), O !== 1) {
          let ne = (O - 1) / (O * 2), J = (O - 1) / (O * 2);
          g = (ne - j) * p, x = (J - Q) * m, _ = p / O, v = m / O;
        }
      }
    }
    S.d(this.TAG, `snapshot x=${g} y=${x} w=${_} h=${v} vw=${p} vh=${m}`);
    let E, b, A, C;
    u / l > p / m ? (E = u, b = u * m / p, A = 0, C = (b - l) / 2) : (b = l, E = l * p / m, A = (E - u) / 2, C = 0);
    const I = u, L = l, R = g / p * E, D = x / m * b, M = Math.max(R, A), w = Math.max(D, C), N = M - A, H = w - C, G = Math.min(R + _ / p * E, A + I) - M, Z = Math.min(D + v / m * b, C + L) - w;
    S.d(this.TAG, `snapshot clip img x=${N} y=${H} w=${G} h=${Z}`), n.width = G, n.height = Z;
    let $ = n.getContext("2d", { alpha: !1 });
    return $ == null || $.drawImage(a, N, H, G, Z, 0, 0, G, Z), n.toDataURL("image/jpeg", h);
  }
  destroy() {
    super.destroy(), this.snapshotCanvas = void 0, this.bufferCanvas = void 0;
  }
}
const P5 = {
  MEDIA_STREAM: [gt.STREAM, gt.STREAM],
  CAMERA_ONLY: [gt.CAMERA, !1],
  CAMERA_MIC: [gt.CAMERA, wt.MIC],
  DISPLAY_ONLY: [gt.SCREENCAST, !1],
  DISPLAY_AUDIO: [gt.SCREENCAST, wt.SCREENCAST],
  DISPLAY_MIC: [gt.SCREENCAST, wt.MIC],
  DISPLAY_MIXED: [gt.SCREENCAST, wt.MIXED],
  MIC_ONLY: [!1, wt.MIC]
};
class k5 extends ve {
  constructor(t) {
    super();
    y(this, "TAG");
    y(this, "options");
    y(this, "endpoint");
    this.TAG = S.traceTag("RTCPusher", t == null ? void 0 : t.traceId), this.options = t, this.init();
  }
  init() {
    const { element: t, audio: i = wt.MIC, video: s = gt.CAMERA, zlmsdpUrl: n, debug: a } = this.options, o = {
      element: t,
      // video/audio 标签
      debug: a,
      // 是否打印日志
      zlmsdpUrl: n,
      // 流地址
      simulcast: !1,
      audio: i,
      video: s,
      mode: Ed.SENDONLY
    }, c = this.endpoint = new wn(o);
    this.initListener(c);
  }
  initListener(t) {
    const {
      WEBRTC_ICE_CANDIDATE_ERROR: i,
      WEBRTC_ON_REMOTE_STREAMS: s,
      WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: n,
      WEBRTC_ON_LOCAL_STREAM: a,
      CAPTURE_STREAM_FAILED: o,
      WEBRTC_ON_CONNECTION_STATE_CHANGE: c
    } = Ge;
    t.on(c, (l) => {
      S.d(this.TAG, " on connection state change", l), this.emit(c, l);
    }), t.on(i, (l) => {
      this.emit(i, l), S.e(this.TAG, i, l);
    }), t.on(s, (l) => {
      this.emit(s, l);
    }), t.on(n, (l) => {
      S.e(this.TAG, n, l), this.emit(n, l), this.destroy();
    }), t.on(a, (l) => {
      this.emit(a, l);
    }), t.on(o, (l) => {
      S.e(this.TAG, o), this.emit(o, l);
    });
  }
  // replaceVideoTrack() {
  //     // this.endpoint?.replaceVideoTrack();
  // }
  destroy() {
    var t, i;
    this.removeAllListeners(), (t = this.endpoint) == null || t.offAll(), (i = this.endpoint) == null || i.close(), this.endpoint = void 0;
  }
}
var w5 = function() {
  var r = navigator.userAgent, e = navigator.appName, t = "" + parseFloat(navigator.appVersion), i = parseInt(navigator.appVersion, 10), s, n, a;
  (n = r.indexOf("OPR/")) != -1 ? (e = "Opera", t = r.substring(n + 4)) : (n = r.indexOf("Opera")) !== -1 ? (e = "Opera", t = r.substring(n + 6), (n = r.indexOf("Version")) !== -1 && (t = r.substring(n + 8))) : (n = r.indexOf("MSIE")) !== -1 ? (e = "IE", t = r.substring(n + 5)) : (n = r.indexOf("Chrome")) !== -1 ? (e = "Chrome", t = r.substring(n + 7)) : (n = r.indexOf("Safari")) !== -1 ? (e = "Safari", t = r.substring(n + 7), (n = r.indexOf("Version")) !== -1 && (t = r.substring(n + 8))) : (n = r.indexOf("Firefox")) !== -1 ? (e = "Firefox", t = r.substring(n + 8)) : (s = r.lastIndexOf(" ") + 1) < (n = r.lastIndexOf("/")) && (e = r.substring(s, n), t = r.substring(n + 1), e.toLowerCase() === e.toUpperCase() && (e = navigator.appName));
  var o = navigator.userAgent.indexOf("Edge") !== -1 && (!!navigator.msSaveOrOpenBlob || !!navigator.msSaveBlob), c = /QQBrowser/.test(navigator.userAgent), l = /MetaSr/.test(navigator.userAgent), d = /BIDUBrowser/.test(navigator.userAgent), h = u(/^liebao/i);
  function u(f, p) {
    var m = window.external || {};
    for (var g in m)
      if (f.test(g))
        return !0;
    return !1;
  }
  return o && (e = "Edge", t = parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10).toString()), c && (e = "QQ", t = parseInt(navigator.userAgent.match(/QQBrowser\/(\d+).(\d+)/)[2], 10).toString()), l && (e = "Sougou", t = parseInt(navigator.userAgent.match(/MetaSr (\d+).(\d+)/)[2], 10).toString()), d && (e = "Baidu", t = parseInt(navigator.userAgent.match(/BIDUBrowser\/(\d+).(\d+)/)[1], 10).toString()), h && (e = "Liebao", t = ""), (a = t.indexOf(";")) !== -1 && (t = t.substring(0, a)), (a = t.indexOf(" ")) !== -1 && (t = t.substring(0, a)), i = parseInt("" + t, 10), isNaN(i) && (t = "" + parseFloat(navigator.appVersion), i = parseInt(navigator.appVersion, 10)), {
    fullVersion: t,
    version: i,
    name: e
  };
}, M5 = function() {
  var r = "Unknown OS", e = {
    Android: function() {
      return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
      return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
      return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
      return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
      return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
      return e.Android() || e.BlackBerry() || e.iOS() || e.Opera() || e.Windows();
    },
    getOsName: function() {
      var t = "Unknown OS";
      return e.Android() && (t = "Android"), e.BlackBerry() && (t = "BlackBerry"), e.iOS() && (t = "iOS"), e.Opera() && (t = "Opera Mini"), e.Windows() && (t = "Windows"), t;
    }
  };
  return e.any() ? r = e.getOsName() : (navigator.appVersion.indexOf("Win") !== -1 && (r = "Windows"), navigator.appVersion.indexOf("Mac") !== -1 && (r = "OSX"), navigator.appVersion.indexOf("X11") !== -1 && (r = "UNIX"), navigator.appVersion.indexOf("Linux") !== -1 && (r = "Linux")), r;
}, B5 = function() {
  var r = !1;
  return (typeof navigator.webkitGetUserMedia < "u" || typeof navigator.mozGetUserMedia < "u" || navigator.mediaDevices && navigator.mediaDevices.getUserMedia) && (r = !0), r;
}, F5 = function() {
  var r = !1;
  return r = ["RTCPeerConnection", "webkitRTCPeerConnection", "mozRTCPeerConnection"].some(function(e) {
    return e in window;
  }), r;
}, O5 = function() {
  var r = !1;
  try {
    var e = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
    if (e) {
      var t = new e({
        iceServers: [{ url: "stun:0" }]
      });
      r = "createDataChannel" in t;
    }
  } catch {
    r = !1;
  }
  return r;
}, Xr = [], U0 = !1, V0 = !1, W0 = !1, N5 = location.protocol === "https:";
navigator.mediaDevices && navigator.mediaDevices.enumerateDevices && (navigator.enumerateDevices = function(r) {
  navigator.mediaDevices.enumerateDevices().then(r);
});
var G5 = function(r) {
  if (!navigator.enumerateDevices && window.MediaStreamTrack && window.MediaStreamTrack.getSources && (navigator.enumerateDevices = window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack)), !navigator.enumerateDevices && navigator.enumerateDevices && (navigator.enumerateDevices = navigator.enumerateDevices.bind(navigator)), !navigator.enumerateDevices) {
    var e = {
      MediaDevices: Xr,
      hasMicrophone: U0,
      hasSpeakers: V0,
      hasWebcam: W0
    };
    r && r(null, e);
    return;
  }
  Xr = [];
  try {
    navigator.enumerateDevices(function(t) {
      t.forEach(function(s) {
        var n = {};
        for (var a in s)
          n[a] = s[a];
        n.kind === "audio" && (n.kind = "audioinput"), n.kind === "video" && (n.kind = "videoinput");
        var o;
        Xr.forEach(function(c) {
          c.id === n.id && c.kind === n.kind && (o = !0);
        }), !o && (n.deviceId || (n.deviceId = n.id), n.id || (n.id = n.deviceId), n.label || (n.label = "Please invoke getUserMedia once.", N5 || (n.label = "HTTPs is required to get label of this " + n.kind + " device.")), n.kind === "audioinput" && (U0 = !0), n.kind === "audiooutput" && (V0 = !0), n.kind === "videoinput" && (W0 = !0), Xr.push(n));
      });
      var i = {
        MediaDevices: Xr,
        hasMicrophone: U0,
        hasSpeakers: V0,
        hasWebcam: W0
      };
      r && r(null, i);
    });
  } catch (t) {
    r && r(t);
  }
}, U5 = w5, V5 = M5, W5 = B5, H5 = F5, Z5 = O5, $5 = G5, De = {}, K5 = location.protocol === "https:";
De.browser = U5();
De.browser["is" + De.browser.name] = !0;
De.osName = V5();
De.getUserMediaSupport = W5();
De.RTCPeerConnectionSupport = H5();
De.dataChannelSupport = Z5();
De.WebSocketSupport = "WebSocket" in window && window.WebSocket.CLOSING === 2;
De.screenCaputringSupport = !1;
De.browser.isChrome && De.browser.version >= 42 && (De.screenCaputringSupport = !0);
K5 || (De.screenCaputringSupport = !1);
De.ORTCSupport = typeof RTCIceGatherer < "u";
De.checkDeviceSupport = $5;
De.RTCatSupport = !1;
(De.browser.isChrome && De.browser.version >= 42 || De.browser.isFirefox && De.browser.version >= 38 || De.browser.isOpera && De.browser.version >= 30 || De.browser.isBaidu && De.browser.version >= 7) && (De.RTCatSupport = !0);
var X5 = De;
const hm = /* @__PURE__ */ Fr(X5);
class um {
  constructor(e, t, i) {
    y(this, "TAG");
    y(this, "rtcPusher");
    y(this, "debug");
    y(this, "traceId");
    y(this, "signalingProxy");
    this.TAG = S.traceTag("RTCTalker", i), this.debug = t, this.signalingProxy = e, this.traceId = i;
  }
  static isSupport() {
    return hm.getUserMediaSupport && hm.RTCPeerConnectionSupport;
  }
  /**
   * 初始化
   * @returns
   */
  async init() {
  }
  destroy() {
    this.stop(), this.signalingProxy = void 0;
  }
  /**
   * 开始对讲
   * @returns
   */
  async start() {
    S.d(this.TAG, "call start talk");
    const [e, t] = P5.MIC_ONLY;
    return this.rtcPusher = new k5({
      traceId: this.traceId,
      debug: this.debug,
      // 是否打印日志
      zlmsdpUrl: async (i) => {
        const s = this.signalingProxy;
        if (s) {
          const { videoCodec: n, audioCodec: a } = s.playerDeviceInfo;
          return i = gg(i, n ? [n] : [], a ? [a] : []), S.d(this.TAG, "talk local sdp", i), s.exchangeSdp(i);
        }
      },
      audio: t,
      video: e
    }), new Promise((i, s) => {
      var n;
      (n = this.rtcPusher) == null || n.on(Ge.WEBRTC_ON_CONNECTION_STATE_CHANGE, (a) => {
        var o;
        S.d(this.TAG, " on connection state change", a), a === _t.failed ? (this.stop(), s(new pt(ki.TalkConnectFailed, "talk channel connect failed"))) : a === _t.connected && ((o = this.signalingProxy) == null || o.notifyDeviceStartPullStream().then(
          (c) => {
            const l = c == null ? void 0 : c.code;
            if (l != 200) {
              let d = new H0(`unknow code: ${l}`);
              return l == -10023 && (d = new pt(ki.TalkBusy, "talk busy")), this.stop(), s(d);
            }
            i(void 0);
          },
          (c) => {
            s(new H0(c.message || c.stack));
          }
        ));
      });
    });
  }
  /**
   * 结束对讲
   */
  async stop() {
    var e, t;
    S.d(this.TAG, "call stop talk"), (e = this.signalingProxy) == null || e.notifyDeviceStopPullStream(), (t = this.rtcPusher) == null || t.destroy(), this.rtcPusher = void 0;
  }
}
const fm = 300, uy = 8e3, Y5 = 16e3;
self.URL = self.URL || self.webkitURL;
const z5 = self.navigator;
class ho extends ve {
  constructor(t, i) {
    super();
    y(this, "TAG");
    y(this, "config");
    y(this, "context");
    y(this, "recorder");
    y(this, "inputStream");
    y(this, "inputBufferSize", 4096);
    y(this, "inputChannels", 1);
    y(this, "outputChannels", this.inputChannels);
    y(this, "emitBuffer");
    y(this, "inputSampleRate", 0);
    //输入采样率
    y(this, "inputSampleBits", 16);
    //输入采样数位 8, 16
    y(this, "status", 0);
    y(this, "sliceSize", 0);
    y(this, "testRecordBuf");
    y(this, "isTestRecord", !1);
    y(this, "onAudioProcess", (t) => {
      let i = Date.now();
      S.d(this.TAG, "_onAudioProcess received data!");
      let s = t.inputBuffer.getChannelData(0);
      this.isTestRecord && (this.testRecordBuf ? this.testRecordBuf = ui(this.testRecordBuf, s) : this.testRecordBuf = s), s = this.compress(s);
      let n = new DataView(new ArrayBuffer(s.length * 2));
      for (let o = 0, c = 0; o < s.length; o++, c += 2) {
        let l = Math.max(-1, Math.min(1, s[o]));
        n.setInt16(c, l < 0 ? l * 32768 : l * 32767, !0);
      }
      this.emitData(n.buffer), S.d(this.TAG, `_onAudioProcess  cost time:${Date.now() - i}ms`);
      let a = 0;
      for (let o = 0; o < s.length; o++)
        a < s[o] && (a = s[o]);
      this.emit("level", Math.round(a * 100));
    });
    this.TAG = S.traceTag("AudioTalk", i);
    const s = {
      sampleBits: 16,
      sampleRate: uy,
      codec: ae.PCM
    };
    if (this.config = Object.assign(s, t), this.context = new (self.webkitAudioContext || self.AudioContext)(), !this.context) {
      this.throwError("get audio context failed");
      return;
    }
    this.inputSampleRate = this.context.sampleRate, this.sliceSize = fm * this.outputChannels * this.config.sampleRate / 1e3 * this.config.sampleBits / 8, S.d(this.TAG, `inputSampleRate:${this.inputSampleRate}. sampleRate:${this.config.sampleRate}`);
  }
  destroy() {
    this.status == 2 && this.throwError("stop audio talk first!"), this.stop(), this.emitBuffer = void 0, this.context && (this.context.close(), this.context = void 0), this.inputStream && (this.inputStream.disconnect(), this.inputStream = void 0), this.recorder && (this.recorder.removeEventListener("audioprocess", this.onAudioProcess), this.recorder.disconnect(), this.recorder = void 0), this.status = 0, this.removeAllListeners();
  }
  static isSupport() {
    return !!z5.mediaDevices.getUserMedia && !!(self.webkitAudioContext || self.AudioContext);
  }
  async start() {
    var i;
    if (this.status !== 1) return this.throwError("please init audio talk");
    const t = this.recorder;
    t && ((i = this.inputStream) == null || i.connect(t), t.addEventListener("audioprocess", this.onAudioProcess, !1), this.context && t.connect(this.context.destination)), this.status = 2;
  }
  async stop() {
    var t, i;
    this.status === 2 && (this.emitBuffer = void 0, (t = this.recorder) == null || t.removeEventListener("audioprocess", this.onAudioProcess), (i = this.recorder) == null || i.disconnect(), this.status = 1, this.emit(
      "end"
      /* end */
    ));
  }
  async init() {
    if (this.status === 0)
      return this.accessMic();
  }
  async accessMic() {
    if (!ho.isSupport()) {
      const t = "unsupport audio talk";
      return this.throwError(t), Promise.reject(new fn(t));
    }
    return self.navigator.mediaDevices.getUserMedia({
      audio: !0,
      //只启用音频
      video: !1
    }).then((t) => {
      const i = this.context;
      i && (this.inputStream = i.createMediaStreamSource(t), this.recorder = (i.createScriptProcessor || i.createJavaScriptNode).apply(i, [this.inputBufferSize, this.inputChannels, this.outputChannels])), this.status = 1;
    }).catch((t) => {
      switch (S.e(this.TAG, "getUserMedia error", t.name + ": " + t.message), t.code || t.name) {
        case "PERMISSION_DENIED":
        case "PermissionDeniedError":
          this.throwError("user refuse");
          break;
        case "NOT_SUPPORTED_ERROR":
        case "NotSupportedError":
          this.throwError("not support mic");
          break;
        case "MANDATORY_UNSATISFIED_ERROR":
        case "MandatoryUnsatisfiedError":
          this.throwError("not found mic");
          break;
        default:
          this.throwError("access mic failed:" + (t.code || t.name));
          break;
      }
    });
  }
  throwError(t) {
    S.e(this.TAG, t);
  }
  emitData(t) {
    let i = new Uint8Array(t);
    for (this.emitBuffer ? this.emitBuffer = ui(this.emitBuffer, i) : this.emitBuffer = i; this.emitBuffer && this.emitBuffer.length >= this.sliceSize; ) {
      let s = this.emitBuffer.slice(0, this.sliceSize).buffer, n = ae.PCM;
      const { codec: a, sampleRate: o } = this.config;
      switch (a) {
        case ae.PCMA:
          try {
            s = Bg.encode(s), n = ae.PCMA;
          } catch (c) {
            S.e(this.TAG, (c == null ? void 0 : c.message) || (c == null ? void 0 : c.stack) || (c == null ? void 0 : c.toString()));
          }
          break;
        case ae.PCMU:
          break;
        case ae.G726:
          break;
        case ae.AAC:
          break;
      }
      this.emit("data", s, n, this.outputChannels, o, fm), this.emitBuffer.length ? this.emitBuffer = this.emitBuffer.slice(this.sliceSize) : this.emitBuffer = void 0;
    }
  }
  compress(t) {
    let i = this.inputSampleRate / this.config.sampleRate, s = t.length / i, n = new Float32Array(s), a = 0, o = 0;
    for (; a < s; )
      n[a] = t[o], o += i, a++;
    return n;
  }
  testWavBlob(t) {
    let i = Date.now(), s = Math.min(this.inputSampleRate, this.config.sampleRate), n = Math.min(this.inputSampleBits, this.config.sampleBits), a = this.outputChannels;
    const o = WavUtil.toWavBlob(t, s, n, a);
    return S.d(this.TAG, `format audio data to wav take ${Date.now() - i} ms`), o;
  }
  testRecordStart() {
    this.isTestRecord = !0, this.init().then(() => {
      this.start();
    }).catch(console.error);
  }
  testRecordPlay() {
    if (this.isTestRecord = !1, this.testRecordBuf) {
      let t = this.compress(this.testRecordBuf), i = this.testWavBlob(t);
      this.testRecordBuf = void 0;
      let s = new self.Audio();
      s.src = URL.createObjectURL(i), s.play();
    }
  }
}
var fy = /* @__PURE__ */ ((r) => (r[r.SELF = 0] = "SELF", r[r.RTC = 1] = "RTC", r))(fy || {});
class j5 extends Po {
  constructor(t, i = {}) {
    super(t);
    y(this, "pluginName", "TalkPlugin");
    y(this, "TAG");
    y(this, "methodList", Object.values(an));
    y(this, "option");
    y(this, "talker");
    const s = t.getTraceId(), n = t.getConfigOption();
    if (this.TAG = S.traceTag(this.pluginName, t.getTraceId()), this.option = i, this.option.talkType === 1 && this.option.signalingWebSocket) {
      const { deviceInfo: a, debug: o = !1, streamChannelId: c = Ri.Main } = n, { iotId: l, productKey: d, deviceName: h, lensId: u } = a, f = a.thingProperties[He.TalkAudioCodec], p = a.thingProperties[He.AudioCodec], m = {
        iotId: l,
        productKey: d,
        deviceName: h,
        lensId: u,
        streamChannelId: c,
        audioCodec: f || p
      }, g = new Ao(this.option.signalingWebSocket, m, Ns.PUSH);
      this.talker = new um(g, o, s);
    } else {
      const a = this.getAudioTalkOptions();
      this.talker = new ho(a, s);
    }
  }
  async callMethod(t, ...i) {
    switch (t) {
      case an.startTalk:
        return this.start();
      case an.stopTalk:
        return this.stop();
    }
  }
  static isSupport() {
    return ho.isSupport() || um.isSupport();
  }
  getAudioTalkOptions() {
    var s, n, a;
    const t = (s = this.player) == null ? void 0 : s.getMediaMeta(), i = ((n = t == null ? void 0 : t.audio) == null ? void 0 : n.codecType) ?? ae.PCMA;
    return { sampleRate: ((a = t == null ? void 0 : t.audio) == null ? void 0 : a.codecType) === ae.G726 ? Y5 : uy, codec: i };
  }
  destroy() {
    var t;
    super.destroy(), (t = this.talker) == null || t.destroy();
  }
  /**
   * 开始对讲
   * @param {*} url 对讲推流地址
   * @returns
   */
  async start() {
    var t;
    return S.i(this.TAG, "call start talk"), (t = this.talker) == null ? void 0 : t.init().then(() => {
      var i;
      return (i = this.talker) == null ? void 0 : i.start();
    });
  }
  async stop() {
    var t;
    return S.i(this.TAG, "call stop talk"), (t = this.talker) == null ? void 0 : t.stop();
  }
}
var py = /* @__PURE__ */ ((r) => (r.GB_LIVE_ADDRESS_GET = "/client/gb/live/address/get", r))(py || {});
const Q5 = "GBDeviceMgr";
var jc = /* @__PURE__ */ ((r) => (r[r.WebRTC = 1] = "WebRTC", r[r.WSS_FLV = 2] = "WSS_FLV", r))(jc || {});
async function J5(r) {
  S.i(Q5, "getGBLiveAddress params=", r);
  const e = py.GB_LIVE_ADDRESS_GET;
  return (await Ae.authRequest(e, r)).data;
}
var hr = ((r) => (r[r.pictureInPictureElement = fr.pictureInPictureElement] = "pictureInPictureElement", r[r.pictureInPictureEnabled = fr.pictureInPictureEnabled] = "pictureInPictureEnabled", r[r.requestPictureInPicture = fr.requestPictureInPicture] = "requestPictureInPicture", r[r.exitPictureInPicture = fr.exitPictureInPicture] = "exitPictureInPicture", r))(hr || {});
class q5 extends Po {
  constructor(t) {
    super(t);
    y(this, "methodList", Object.values(hr));
    y(this, "TAG");
    y(this, "pluginName", Li.PictureInPicturePlug);
    this.TAG = S.traceTag(this.pluginName, t.getTraceId());
  }
  async callMethod(t, ...i) {
    switch (t) {
      case hr.pictureInPictureElement:
        return this.pictureInPictureElement();
      case hr.pictureInPictureEnabled:
        return this.pictureInPictureEnabled();
      case hr.requestPictureInPicture:
        return this.requestPictureInPicture();
      case hr.exitPictureInPicture:
        return this.exitPictureInPicture();
    }
  }
  pictureInPictureElement() {
    return document.pictureInPictureElement;
  }
  pictureInPictureEnabled() {
    return document.pictureInPictureEnabled;
  }
  /**
   * 退出画中画
   */
  async exitPictureInPicture() {
    return this.pictureInPictureElement() ? document.exitPictureInPicture() : Promise.resolve();
  }
  /**
   * 进入画中画
   * @returns
   */
  async requestPictureInPicture() {
    var i;
    const t = (i = this.player) == null ? void 0 : i.getVideoRender();
    return t ? t instanceof HTMLVideoElement && this.pictureInPictureEnabled() ? t.requestPictureInPicture() : Promise.reject(new fn("not support pictureInPicture")) : Promise.reject(new fn("wait play"));
  }
}
const Ds = document, pm = ye, mm = {
  playMode: Er.DEVICE,
  videoWrapper: "",
  debug: !1,
  bufferWaitTimeMS: 3e4,
  playLimitDuration: void 0,
  streamChannelId: Ri.Main,
  lensId: void 0,
  disableP2P: !1,
  disableCMS: !1
}, my = {
  exitFullscreen: "fullscreenchange",
  mozCancelFullScreen: "mozfullscreenchange",
  webkitExitFullscreen: "webkitfullscreenchange",
  msExitFullscreen: "MSFullscreenChange"
};
function gm() {
  var e;
  const r = (e = Object.entries(my).find(([t]) => Ds[t])) == null ? void 0 : e[1];
  return r || S.e(S.GLOBAL_TAG, "unsupport fullscreen change event"), r;
}
class gy {
  constructor(e) {
    y(this, "TAG");
    y(this, "playerWrapper");
    y(this, "signalingWebSocket");
    y(this, "signalingProxy");
    y(this, "videoRenderWrapper", null);
    y(this, "options", mm);
    y(this, "realPlayer", null);
    y(this, "traceId", km());
    y(this, "eventEmitter", new ve());
    y(this, "rtcLiveStrategy");
    y(this, "isPause", !1);
    y(this, "isPlaying", !1);
    y(this, "lastSeekParam");
    y(this, "lastUpdateTime", 0);
    y(this, "plugins", /* @__PURE__ */ new Map());
    y(this, "waitingCheckTimer", -1);
    y(this, "videoRenderWrapperId", "");
    y(this, "onCanPlay", () => {
      var e;
      S.i(this.TAG, "onCanPlay"), (e = this.eventEmitter) == null || e.emit(Gt.canplay);
    });
    y(this, "onTimeUpdate", (e) => {
      this.isPlaying || (this.isPlaying = !0, this.eventEmitter.emit(Gt.playing));
      const t = Qi();
      t - this.lastUpdateTime < 500 || (this.startWaitingCheck(), this.lastUpdateTime = t, this.isPlayback ? e = this.lastSeekParam.beginTime + e : e = Date.now(), this.eventEmitter.emit(Gt.timeupdate, e));
    });
    y(this, "onPlayerError", (e) => {
      S.e(this.TAG, "onPlayerError", e), this.isPlaying = !1, this.destroyPlayer(), this.eventEmitter.emit(Gt.error, e);
    });
    y(this, "onPlayerEnded", () => {
      S.i(this.TAG, "onPlayerEnded"), this.isPlaying = !1, this.destroyPlayer(), this.eventEmitter.emit(Gt.ended);
    });
    if (this.options = Object.assign({}, mm, e), this.TAG = S.traceTag("RTCXWebPlayer", this.traceId), e.debug && (S.ENABLE_DEBUG = S.ENABLE_VERBOSE = !0), this.playerWrapper = typeof e.videoWrapper == "string" ? Ds.querySelector(e.videoWrapper) : e.videoWrapper, S.i(this.TAG, navigator.userAgent), this.options.playMode === Er.DEVICE && !e.deviceInfo)
      throw new Rs("lost options.deviceInfo ");
    if (this.options.playMode === Er.GB_DEVICE)
      if (e.gbDeviceInfo) {
        if (!e.gbDeviceInfo.iotId && !(e.gbDeviceInfo.productKey && e.gbDeviceInfo.deviceName))
          throw new Rs("Missing parameter iotId or productKey&DeviceName in gbDeviceInfo");
      } else throw new Rs("lost options.gbDeviceInfo ");
    this.init();
  }
  /**
   * 播放
   * @param url - 播放地址
   * @param type - 地址播放类型
   */
  async playUrl(e, t) {
    this.isPause = !1, this.realPlayer ? (this.destroyPlayer(), setTimeout(() => this.delayplayUrl(e, t), 50)) : this.delayplayUrl(e, t);
  }
  async playGBDevice() {
    const [e] = await $n.isSupport(de.H265, ae.NONE), t = e ? oi.WebRTC : oi.FLV, { productKey: i, deviceName: s, iotId: n, channelNo: a = "" } = this.options.gbDeviceInfo || {}, o = async (c, l) => {
      const d = c == oi.WebRTC;
      let h;
      d && (h = l);
      const u = {
        productKey: i,
        deviceName: s,
        iotId: n,
        channelNo: a,
        protocol: d ? jc.WebRTC : jc.WSS_FLV,
        sdp: h
      }, f = await J5(u);
      return (d ? f.sdp : f.url) ?? "";
    };
    this.delayplayUrl(o, t);
  }
  /**
   * 播放
   * @param url - 播放地址或地址获取异步方法
   * @param type - 可选 地址播放类型, 当url为PlayUrlGetter时，从PlayUrlGetter返回值中获取
   */
  async delayplayUrl(e, t) {
    var f;
    const { debug: i = !1, bufferWaitTimeMS: s = 0, playLimitDuration: n, muted: a, hasVideo: o, hasAudio: c, gbDeviceInfo: l, webRTCMediaDecodeCallback: d } = this.options, h = this.videoRenderWrapper;
    if (!h)
      throw new Rs("lost video render wrapper");
    const u = {
      traceId: this.traceId,
      videoRenderWrapperId: this.videoRenderWrapperId,
      // enableWorkerForMSE: true,
      hasVideo: o !== !1,
      hasAudio: c !== !1,
      muted: a === !0,
      videoWrapper: h,
      debug: i,
      bufferWaitTimeMS: s,
      playLimitDuration: n,
      deferLoadAfterSourceOpen: !1,
      enableStashBuffer: !this.isPlayback,
      stashInitialSize: 128 * 1024
    };
    switch (u.extraOptions = u.extraOptions || {}, this.signalingProxy && (u.extraOptions.signalingProxy = this.signalingProxy), d && (u.extraOptions.mediaDecodeCallback = d), t) {
      case oi.FLV:
        typeof e == "function" && (e = await e(oi.FLV)), this.realPlayer = new Ot.MSEPlayer(
          {
            url: e,
            type: t
          },
          u
        );
        break;
      case oi.HLS:
        const p = {
          url: e,
          type: On.HLS
        };
        this.realPlayer = new am(p, u);
        break;
      case oi.WebRTC: {
        const { iotId: m = "", productKey: g = "", deviceName: x = "", channelNo: _ } = l || {}, v = {
          iotId: m,
          productKey: g,
          deviceName: x,
          channelNo: _,
          streamChannelId: 0
        };
        this.realPlayer = new $n(
          {
            type: On.WEBRTC,
            url: e
          },
          u,
          v
        );
        break;
      }
      default:
        throw new fn("unsupport url type");
    }
    if (this.realPlayer) {
      this.initPlayerListener(this.realPlayer), this.realPlayer.load(), S.d(this.TAG, "play url load");
      try {
        await ((f = this.realPlayer) == null ? void 0 : f.play());
      } catch (p) {
        S.e(this.TAG, "auto play error", p), this.eventEmitter.emit(Gt.pause);
      }
    }
  }
  registerPlugin(e, t, i) {
    const s = new t(this, i);
    this.plugins.set(e, s);
  }
  unregisterPlugin(e) {
    const t = this.getPlugin(e);
    t && (t.destroy(), this.plugins.delete(e));
  }
  getPlugin(e) {
    return this.plugins.get(e);
  }
  getAudioRender() {
    var e;
    return (e = this.realPlayer) == null ? void 0 : e.audioRender;
  }
  getVideoRender() {
    var e;
    return (e = this.realPlayer) == null ? void 0 : e.videoRender;
  }
  getRootElement() {
    var e;
    return (e = this.playerWrapper) == null ? void 0 : e.querySelector("." + Ur);
  }
  getMediaMeta() {
    var e;
    return (e = this.realPlayer) == null ? void 0 : e.metaData;
  }
  getTraceId() {
    return this.traceId;
  }
  getConfigOption() {
    return this.options;
  }
  /**
   * 监听全屏状态变化
   * @param listener - 加调
   */
  static onFullscreenChange(e) {
    const t = gm();
    S.d(S.GLOBAL_TAG, "onFullscreenChange changeEvent=" + t), t && Ds.addEventListener(t, e, !1);
  }
  /**
   * 移除监听全屏状态变化
   * @param listener - 加调
   */
  static offFullscreenChange(e) {
    const t = gm();
    S.d(S.GLOBAL_TAG, "offFullscreenChange changeEvent=" + t), t && Ds.removeEventListener(t, e);
  }
  /**
   * 全屏
   *
   * @param domElement - Dom元素
   * @public
   */
  static requestFullscreen(e) {
    S.i(S.GLOBAL_TAG, "call requestFullscreen", e);
    let t = e.requestFullscreen || e.mozRequestFullScreen || e.webkitRequestFullscreen || e.msRequestFullscreen;
    t && t.call(e);
  }
  /**
   * 判断当前是否全屏
   * @public
   */
  static isFullscreen() {
    S.i(S.GLOBAL_TAG, "call isFullscreen");
    const e = Ds;
    return !!(e.fullscreenElement || e.mozFullScreenElement || e.webkitFullscreenElement || e.msFullscreenElement);
  }
  /**
   * 浏览器退出全屏
   * @public
   */
  static exitFullscreen() {
    if (S.i(S.GLOBAL_TAG, "call exitFullscreen"), !gy.isFullscreen()) return;
    const e = Ds;
    let t = Object.keys(my).find((i) => e[i]);
    t && e[t]();
  }
  on(e, t) {
    var i;
    (i = this.eventEmitter) == null || i.on(e, t);
  }
  off(e, t) {
    var i;
    (i = this.eventEmitter) == null || i.off(e, t);
  }
  async destroy() {
    this.eventEmitter.removeAllListeners(), this.pause(), this.destroyPlayer(), this.signalingWebSocket && (this.signalingWebSocket = void 0), Object.values(this.plugins).forEach((e) => e.destroy()), this.plugins.clear();
  }
  async play() {
    var e;
    if (this.options.playMode === Er.GB_DEVICE)
      return this.playGBDevice();
    this.lastSeekParam = void 0, this.isPause = !1, await this.createPlayer();
    try {
      await ((e = this.realPlayer) == null ? void 0 : e.play());
    } catch (t) {
      S.e(this.TAG, "auto play error", t), this.eventEmitter.emit(Gt.pause);
    }
  }
  async pause() {
    var e;
    this.isPause || (this.stopWaitingCheck(), this.isPause = !0, (e = this.realPlayer) == null || e.pause(), this.eventEmitter.emit(Gt.pause));
  }
  async seek(e) {
    var o, c;
    S.i(this.TAG, "call seek", e);
    const { isSDCard: t, filename: i } = e;
    this.isPause = !1;
    const { isSDCard: s, filename: n } = this.lastSeekParam || {}, a = this.realPlayer && this.lastSeekParam && (s && t && n == i || !s && !t);
    if (this.lastSeekParam = e, S.i(this.TAG, "canReuse player=" + a), a)
      (c = this.realPlayer) == null || c.seekTo(e);
    else {
      await this.createPlayer(e);
      try {
        await ((o = this.realPlayer) == null ? void 0 : o.play());
      } catch (l) {
        S.e(this.TAG, "seek auto play error", l), this.eventEmitter.emit(Gt.pause);
      }
    }
  }
  get duration() {
    return 0;
  }
  get volume() {
    var e;
    return ((e = this.realPlayer) == null ? void 0 : e.volume) ?? 0;
  }
  set volume(e) {
    this.realPlayer && (this.realPlayer.volume = e);
  }
  get muted() {
    var e;
    return ((e = this.realPlayer) == null ? void 0 : e.muted) ?? !1;
  }
  set muted(e) {
    this.realPlayer && this.options.hasAudio !== !1 && (this.realPlayer.muted = e), this.options.muted = e;
  }
  get currentTime() {
    var e;
    return ((e = this.realPlayer) == null ? void 0 : e.currentTime) ?? 0;
  }
  get playbackRate() {
    var e;
    return ((e = this.realPlayer) == null ? void 0 : e.playbackRate) ?? 0;
  }
  get isPlayback() {
    return !!this.lastSeekParam;
  }
  get isPlaySDCard() {
    var e;
    return ((e = this.lastSeekParam) == null ? void 0 : e.isSDCard) ?? !1;
  }
  async init() {
    if (!this.createPlayerDom()) return;
    const e = this.options.deviceInfo;
    if (e) {
      Object.keys(e.thingProperties).length || await fd(e.iotId).then((i) => e.thingProperties = i);
      const t = [this.getRtcLiveStrategy(), this.getPlayLimitDuration()];
      await Promise.allSettled(t);
    }
    if (this.registerPlugin(Li.ZoomPlug, L5), this.registerPlugin(Li.SnapshotPlugin, D5), this.registerPlugin(Li.PictureInPicturePlug, q5), e) {
      const t = {
        talkType: fy.RTC,
        signalingWebSocket: this.getSignalingWebSocket()
      };
      this.registerPlugin(Li.TalkPlug, j5, t);
    }
    this.eventEmitter.emit(Gt.inited);
  }
  async getRtcLiveStrategy() {
    const { deviceInfo: e } = this.options;
    if (!e) return this.rtcLiveStrategy;
    const t = Date.now();
    if (!this.rtcLiveStrategy && e.isSupportP2P) {
      const i = await sc.getDeviceEntity(e.iotId, ms.LIVE_PLAY_STRATEGY);
      try {
        this.rtcLiveStrategy = JSON.parse(i);
      } catch {
        S.e(this.TAG, `getRtcLiveStrategy parse error:${i}`);
      }
    }
    return S.i(this.TAG, `getRtcLiveStrategy take ${Date.now() - t}ms`, this.rtcLiveStrategy), this.rtcLiveStrategy;
  }
  async getPlayLimitDuration() {
    let { playLimitDuration: e, deviceInfo: t } = this.options;
    const i = {
      payLiveDuration: 20 * 60,
      liveDuration: 5 * 60
    };
    if (!t) return this.options.playLimitDuration ?? i.liveDuration;
    const { iotId: s } = t, n = Date.now();
    if (!e) {
      const a = [
        T1.request({ iotId: s }, !1),
        sc.getDeviceEntity(s, ms.LIVE_PLAY_DURATION_LIMIT).then((h) => JSON.parse(h)).catch(() => i)
      ], o = await Promise.allSettled(a), c = o[0].status === "fulfilled" ? o[0].value : void 0, l = o[1].status === "fulfilled" ? o[1].value : void 0;
      e = (c == null ? void 0 : c.status) == 1 ? l == null ? void 0 : l.payLiveDuration : l == null ? void 0 : l.liveDuration, this.options.playLimitDuration = e;
    }
    return S.i(this.TAG, `getPlayLimitDuration take ${Date.now() - n}ms`, e), e;
  }
  createPlayerDom() {
    S.i(this.TAG, "createPlayerDom");
    let e = this.playerWrapper;
    if (!e)
      return S.e(this.TAG, "playerWrapper lost", this.options), !1;
    const { offsetWidth: t, offsetHeight: i } = e;
    if (t <= 0 || i <= 0)
      return S.e(this.TAG, `playerWrapper invalid, offsetWidth=${t}, offsetHeight=${i}`, e), !1;
    let s = this.traceId;
    const n = Xs, a = Fm, o = `${a}-${s}`;
    this.videoRenderWrapperId = o;
    const c = `<div class="${Ur}" id="${n}-${s}"><div class="${fa}" ><div class="${a}" id="${o}"></div><div class="${n}-mask-cover"></div></div><div class="${n}-loading"></div><div class="${n}-paused"></div></div>`;
    let l = `.${Ur},.${fa}{display: block;background: #000;}.${fa},.${Ur}{width: 100%; height: 100%;position:relative;}.${Ur}{overflow:hidden;}.${a},.${n}-mask-cover {position: absolute;top: 0;bottom: 0;left: 0;right: 0;background:no-repeat center;background-size: contain;}.${a}{display:flex;justify-content: center; align-items: center;}.${a} canvas,.${a} video{width:100%;height:100%;object-fit:contain;}.${a}.w-auto canvas,.${a}.w-auto video{width: auto;}`, d = Ds, h = `${n}-style`;
    if (!d.querySelector("#" + h)) {
      let u = d.getElementsByTagName("head")[0], f = d.createElement("style");
      f.innerHTML = l, f.id = h, u.appendChild(f);
    }
    return e.innerHTML = c, this.videoRenderWrapper = e.querySelector(`.${a}`), this.videoRenderWrapper || S.e(this.TAG, `class=.${a} videoRenderWrapper=`, this.videoRenderWrapper), this.fixChromeVideoFlashBug(), !0;
  }
  fixChromeVideoFlashBug() {
    const e = pm.chrome || pm.edge, t = this.playerWrapper;
    e && t && (t.style.backdropFilter = "blur(0px)", t.style.transform = "translateZ(0)");
  }
  getSignalingWebSocket() {
    let e = this.signalingWebSocket;
    return e || (e = this.signalingWebSocket = Ii(this.traceId)), e;
  }
  getVideoCodec() {
    var l, d, h, u;
    const { deviceInfo: e, lensId: t = 0, streamChannelId: i = Ri.Main } = this.options, s = e == null ? void 0 : e.thingProperties;
    if (!s) return;
    const n = s[He.CodecList];
    if (n)
      try {
        const f = JSON.parse(n), p = (u = (h = (d = (l = f == null ? void 0 : f.Lens) == null ? void 0 : l.find((m) => m.Id == t)) == null ? void 0 : d.Channel) == null ? void 0 : h.find((m) => m.Id == i)) == null ? void 0 : u.VideoCodec;
        if (p) return p;
      } catch {
        S.e(this.TAG, "getVideoCodec parse codecList");
      }
    const a = s[He.VideoCodec], o = s[He.SubVideoCodec];
    return (i == Ri.Main ? a : o) || a;
  }
  getAudioCodec() {
    var l, d, h, u;
    const { deviceInfo: e, lensId: t = 0, streamChannelId: i = Ri.Main } = this.options, s = e == null ? void 0 : e.thingProperties;
    if (!s) return;
    const n = s[He.CodecList];
    if (n)
      try {
        const f = JSON.parse(n), p = (u = (h = (d = (l = f == null ? void 0 : f.Lens) == null ? void 0 : l.find((m) => m.Id == t)) == null ? void 0 : d.Channel) == null ? void 0 : h.find((m) => m.Id == i)) == null ? void 0 : u.AudioCodec;
        if (p) return p;
      } catch {
        S.e(this.TAG, "getVideoCodec parse codecList");
      }
    const a = s[He.AudioCodec], o = s[He.SubAudioCodec];
    return (i == Ri.Main ? a : o) || a;
  }
  async createPlayer(e) {
    this.realPlayer && this.destroyPlayer(), S.i(this.TAG, `createPlayer  player=${!!this.realPlayer}`, e);
    const {
      deviceInfo: t,
      debug: i = !1,
      bufferWaitTimeMS: s = 0,
      playLimitDuration: n,
      streamChannelId: a = Ri.Main,
      muted: o,
      hasVideo: c,
      hasAudio: l,
      disableP2P: d,
      disableCMS: h,
      webRTCMediaDecodeCallback: u
    } = this.options;
    if (!t)
      throw new Rs("lost options.deviceInfo");
    const f = this.videoRenderWrapper;
    if (!f)
      throw new Rs("lost video render wrapper");
    const { isSDCard: p } = this.lastSeekParam || {}, { iotId: m, productKey: g, deviceName: x, lensId: _ } = t, v = this.getVideoCodec(), E = this.getAudioCodec(), b = {
      iotId: m,
      productKey: g,
      deviceName: x,
      lensId: _,
      streamChannelId: a,
      seekParam: e,
      videoCodec: v,
      audioCodec: E
    };
    if (!this.isPlayback || p) {
      const A = mb(v), C = gb(E), [I, L] = await $n.isSupport(A, C);
      let R = this.getSignalingWebSocket();
      const D = {
        type: On.WEBRTC
      }, M = {
        traceId: this.traceId,
        hasVideo: c !== !1,
        hasAudio: l !== !1,
        muted: o === !0,
        videoWrapper: f,
        debug: i,
        bufferWaitTimeMS: s,
        playLimitDuration: n,
        disableCMS: h,
        disableP2P: d,
        playStrategy: this.rtcLiveStrategy
      };
      if (u && (M.extraOptions = M.extraOptions || {}, M.extraOptions.mediaDecodeCallback = u), I || c === !1 && L)
        this.realPlayer = new $n(D, M, b, R);
      else {
        S.w(this.TAG, `device codec type. video=${v} audio=${E}`);
        const w = p ? Ns.SDCARD : Ns.LIVE;
        this.signalingProxy = new Ao(R, b, w);
        const N = async () => {
          var G, Z;
          return e && ((G = this.signalingProxy) == null || G.seekSdCard(e, yt.CMS)), await ((Z = this.signalingProxy) == null ? void 0 : Z.exchangeSdp("", void 0, Na.FLV));
        };
        this.delayplayUrl(N, oi.FLV);
        return;
      }
    } else if (e) {
      const A = {
        type: On.HLS
      }, C = {
        traceId: this.traceId,
        hasVideo: c !== !1,
        hasAudio: l !== !1,
        muted: o === !0,
        videoWrapper: f,
        debug: i,
        bufferWaitTimeMS: s,
        playLimitDuration: n
      };
      this.realPlayer = new am(A, C, b);
    }
    this.realPlayer && (this.initPlayerListener(this.realPlayer), this.realPlayer.load());
  }
  initPlayerListener(e) {
    e.on(z.CAN_PLAY, this.onCanPlay), e.on(z.TIME_UPDATE, this.onTimeUpdate), e.on(z.ERROR, this.onPlayerError), e.on(z.PLAY_ENDED, this.onPlayerEnded);
  }
  stopWaitingCheck() {
    clearTimeout(this.waitingCheckTimer);
  }
  startWaitingCheck() {
    this.stopWaitingCheck(), this.waitingCheckTimer = setTimeout(() => {
      this.isPlaying = !1, this.eventEmitter.emit(Gt.waiting);
    }, 1e3);
  }
  destroyPlayer() {
    S.i(this.TAG, "destroyPlayer start"), this.stopWaitingCheck(), this.realPlayer && this.realPlayer.destroy(), this.realPlayer = null, S.i(this.TAG, "destroyPlayer end");
  }
}
class w6 {
  constructor(e) {
    y(this, "deviceInfo");
    y(this, "realPanel");
    this.deviceInfo = e, this.realPanel = new LS(this.deviceInfo);
  }
  supportProperty(e) {
    return this.realPanel.supportProperty(e);
  }
  supportService(e) {
    return this.realPanel.supportService(e);
  }
  getThingProperties() {
    return this.realPanel.getThingProperties();
  }
  async setProperties(e, t) {
    return this.realPanel.setProperties(e, t);
  }
  setPropertiesTimeout(e) {
    this.realPanel.setPropertiesTimeout(e);
  }
  getThingTsl() {
    return this.realPanel.getThingTsl();
  }
  invokeService(e, t, i = !1, s, n) {
    return this.realPanel.invokeService(e, t, i, s, n);
  }
  subscribe(e) {
    this.realPanel.subscribe(e);
  }
  unsubscribe(e) {
    this.realPanel.unsubscribe(e);
  }
  destroy() {
    this.realPanel.destroy();
  }
}
var ci = /* @__PURE__ */ ((r) => (r[r.STATE_IDLE = 0] = "STATE_IDLE", r[r.STATE_SUCCESS = 1] = "STATE_SUCCESS", r[r.STATE_ERROR = 2] = "STATE_ERROR", r))(ci || {});
const M6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  DataChannelStateEnum: ci
}, Symbol.toStringTag, { value: "Module" }));
var _y = /* @__PURE__ */ ((r) => (r[r.GET_SDCARD_PIC = 1001] = "GET_SDCARD_PIC", r[r.START_PANORAMIC_STITCHING = 1003] = "START_PANORAMIC_STITCHING", r[r.RECEIVE_PANORAMIC_IMG = 1005] = "RECEIVE_PANORAMIC_IMG", r[r.STOP_PANORAMIC_STITCHING = 1007] = "STOP_PANORAMIC_STITCHING", r))(_y || {}), yy = /* @__PURE__ */ ((r) => (r.GET_SDCARD_PIC = "thing.service.GetPic", r.START_PANORAMIC_STITCHING = "thing.service.StartImageStitching", r.RECEIVE_PANORAMIC_IMG = "thing.service.ImageStitching", r.STOP_PANORAMIC_STITCHING = "thing.service.StopImageStitching", r))(yy || {});
const Br = "DataChannelMgr", Rr = [];
function e6(r, e) {
  const { iotId: t, productKey: i, deviceName: s } = r, n = i + s;
  if (Ey(n))
    S.i(Br, `data channel cache exists: device=${n}`);
  else {
    const c = {
      zlmsdpUrl: e,
      deviceInfo: {
        iotId: t,
        productKey: i,
        deviceName: s,
        streamChannelId: 0
      },
      channelMode: yt.CMS,
      traceId: _o(),
      video: !1,
      audio: !1,
      usedatachannel: !0
      // debug: true
    };
    let l;
    r.isLanDevice(), l || (l = new on(c)), xy(n, l), S.i(Br, `data channel created ${n}`);
  }
  return i6(n);
}
function t6(r) {
  if (r.dataChannelParentCount === 0) return;
  const { productKey: e, deviceName: t } = r.deviceInfo, i = e + t;
  if (!vy(r)) {
    Qc(i);
    return;
  }
  if (r.dataChannelParentCount--, r.dataChannelParentCount <= 0) {
    Qc(i);
    return;
  }
  xy(i, r);
}
function xy(r, e) {
  e.dataChannelParentCount > 0 && e.dataChannelParentCount--, !Ey(r) && (S.d(Br, `addItem deviceUniqueKey=${r}  cacheSize=${Rr.length}`), Rr.push({ deviceUniqueKey: r, dataChannel: e }));
}
function vy(r) {
  return r != null && r.connectStatus != _t.failed;
}
function Qc(r) {
  S.d(Br, `removeItem deviceUniqueKey=${r}`);
  let e = 0;
  for (; e < Rr.length; ) {
    const t = Rr[e];
    if (t.deviceUniqueKey === r) {
      Rr.splice(e, 1), s6(t);
      continue;
    }
    e++;
  }
}
function i6(r) {
  S.d(Br, `fetch data channel. deviceUniqueKey=${r}`);
  const e = Sy(r);
  if (!e.length) return null;
  const t = e.at(0), i = t == null ? void 0 : t.dataChannel;
  return i && i.dataChannelParentCount++, i ?? null;
}
function Ey(r) {
  const e = Sy(r);
  return e.length ? !!e.find((i) => {
    const s = i.dataChannel, n = vy(s);
    return n || Qc(r), n;
  }) : !1;
}
function Sy(r) {
  const e = [];
  for (const t of Rr)
    t.deviceUniqueKey == r && e.push(t);
  return e;
}
function s6(r) {
  const e = r.deviceUniqueKey, t = r.dataChannel;
  t != null && (t.dataChannelParentCount = 0);
  const i = t == null ? void 0 : t.channelMode;
  S.d(Br, `releaseCache. deviceUniqueKey=${e} ${i}`), t == null || t.destroy(), r.dataChannel = void 0;
}
const _m = `${Bt.CMD_THING_INVOKE_SERVICE}.${rt.DataChannelStatus}`, fo = class fo {
  /*
   *
   * @param deviceInfo - 设备信息
   * @param retryMax  连接重试次数,默认1 重试一次
   */
  constructor(e, t = fo.DEFAULT_RETRY_MAX) {
    y(this, "TAG", "SigCmdDataChannel");
    y(this, "deviceInfo");
    y(this, "retryMax");
    y(this, "sendMessageCallbackKeys", /* @__PURE__ */ new Map());
    y(this, "mEventEmitter", new ve());
    y(this, "mDataChannelState", ci.STATE_IDLE);
    y(this, "mDataChannel");
    y(this, "mOnDataChannelListener");
    y(this, "retryCnt", 0);
    y(this, "signalingWebSocket");
    y(this, "signalingProxy");
    y(this, "datachannelStreamName");
    y(this, "receivedBuffer", new Uint8Array(0));
    //CMS DATACHANNEL
    y(this, "onDataChannelStatusCallback", (e) => {
      var n;
      const t = e.params, i = t.Stream, s = Number(t.Status);
      this.datachannelStreamName === i && (s === 1 ? (n = this.mDataChannel) == null || n.init() : (S.e(this.TAG, "device create channel error"), this.onRTCConnectStateChanged(_t.failed)));
    });
    y(this, "onRTCConnectStateChanged", (e) => {
      if (S.i(this.TAG, `${this.getChannelMode()} onRTCConnectStateChanged state=${e}`), e == _t.failed) {
        if (this.retryMax > 0 && this.retryCnt < this.retryMax) {
          this.retryCnt++, this.releaseChannel(!0), setTimeout(this.initChannel, 1e3);
          return;
        }
        this.onDataChannelStatusChanged(ci.STATE_ERROR);
      } else e == _t.connected && (this.retryCnt = 0);
    });
    y(this, "onChannelOpen", () => {
      S.i(this.TAG, "open channel open"), this.onDataChannelStatusChanged(ci.STATE_SUCCESS);
    });
    y(this, "onChannelError", () => {
      S.e(this.TAG, "open channel error"), this.onRTCConnectStateChanged(_t.failed);
    });
    y(this, "onChannelMessage", (e) => {
      const { data: t } = e;
      if (t instanceof ArrayBuffer)
        this.parseArrayBuffer(t);
      else if (t instanceof Blob) {
        let i = new FileReader();
        i.onload = () => {
          this.parseArrayBuffer(i.result);
        }, i.readAsArrayBuffer(t);
      } else {
        let i = {
          code: -1,
          msg: "Unsupported data channel message type: " + t.constructor.name
        };
        S.e(this.TAG, "onChannelMessage", i);
      }
    });
    y(this, "parseChannelMessage", (e, t, i) => {
      var a;
      if (e >= 0 && e <= 1e3) {
        (a = this.mOnDataChannelListener) == null || a.onData(e, t);
        return;
      }
      const s = ri.unit8Array2String(i);
      S.i(this.TAG, `onData, cmdId=${e}, data=${s}`);
      let n;
      try {
        n = JSON.parse(s);
      } catch {
      }
      if ((e & 1) == 1) {
        if (n) {
          const o = n;
          this.mEventEmitter.emit(o.method, n, t);
        }
      } else if (n) {
        const o = n;
        this.mEventEmitter.emit(o.method + o.id, o, t);
      }
    });
    y(this, "initChannel", async () => {
      var e, t, i, s, n, a, o;
      if (await this.checkThingProperties(), this.mDataChannel = e6(this.deviceInfo, async (c) => {
        var l;
        return (l = this.signalingProxy) == null ? void 0 : l.exchangeSdp(c, this.datachannelStreamName);
      }), (e = this.mDataChannel) == null || e.addListener(Ge.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.onRTCConnectStateChanged), (t = this.mDataChannel) == null || t.addListener(Ge.WEBRTC_ON_DATA_CHANNEL_OPEN, this.onChannelOpen), (i = this.mDataChannel) == null || i.addListener(Ge.WEBRTC_ON_DATA_CHANNEL_ERR, this.onChannelError), (s = this.mDataChannel) == null || s.addListener(Ge.WEBRTC_ON_DATA_CHANNEL_MSG, this.onChannelMessage), S.i(this.TAG, `${this.getChannelMode()} init connectStatus = ${(n = this.mDataChannel) == null ? void 0 : n.connectStatus}`), ((a = this.mDataChannel) == null ? void 0 : a.connectStatus) == _t.connected) {
        this.onDataChannelStatusChanged(ci.STATE_SUCCESS);
        return;
      }
      if (((o = this.mDataChannel) == null ? void 0 : o.channelMode) == yt.CMS) {
        this.signalingWebSocket = Ii(), this.signalingWebSocket.on(_m, this.onDataChannelStatusCallback);
        const { iotId: c, productKey: l, deviceName: d } = this.deviceInfo, h = {
          iotId: c,
          productKey: l,
          deviceName: d,
          streamChannelId: Ri.Main,
          seekParam: {
            isSDCard: !0,
            beginTime: 0
            //无用途
          }
        };
        this.signalingProxy = new Ao(this.signalingWebSocket, h, Ns.LIVE), this.signalingProxy.notifyDeviceCreateChannel(this.datachannelStreamName);
      }
    });
    this.deviceInfo = e, this.retryMax = t, this.datachannelStreamName = `${e.deviceName}_data_${Date.now()}_web_cms`, this.isSupport() ? this.initChannel() : S.w(this.TAG, "unsupport data channel");
  }
  /**
   * 协议定义：https://xiangsutech.feishu.cn/wiki/OdJHwsLoZieHLzktaGDctkg3nfB
   * @param arraybuffer
   */
  parseArrayBuffer(e) {
    this.receivedBuffer = ui(this.receivedBuffer, new Uint8Array(e));
    const t = this.receivedBuffer.length;
    if (t < 9) return;
    const i = new DataView(this.receivedBuffer.buffer), s = i.getUint16(0, !1), n = i.getUint16(3, !1), a = i.getUint32(5), o = s - 9, c = s + a;
    if (t < c) return;
    let l = 9, d = l + o;
    const h = this.receivedBuffer.slice(l, d);
    l = d, d = l + a;
    const u = this.receivedBuffer.slice(l, d);
    this.receivedBuffer = t > c ? this.receivedBuffer.slice(c) : new Uint8Array(0), this.parseChannelMessage(n, u, h);
  }
  /**
   * 销毁
   */
  destroy() {
    var e;
    S.i(this.TAG, `${this.getChannelMode()} destroy data channel`), this.mDataChannelState != ci.STATE_IDLE && this.releaseChannel(!1), this.mOnDataChannelListener = void 0, this.mEventEmitter.removeAllListeners();
    for (const t of this.sendMessageCallbackKeys.values())
      clearTimeout(t);
    this.sendMessageCallbackKeys.clear(), (e = this.signalingWebSocket) == null || e.off(_m, this.onDataChannelStatusCallback);
  }
  /**
   * 设置监听
   * @param onDataChannelListener - 监听
   */
  setOnDataChannelListener(e) {
    this.mOnDataChannelListener = e;
  }
  isSupport() {
    return this.deviceInfo.supportSdkAbility(Ir.SDK_ABILITY_DATA_CHANNEL);
  }
  on(e, t) {
    this.mEventEmitter.on(e, t);
  }
  off(e, t) {
    this.mEventEmitter.off(e, t);
  }
  isValidChannel() {
    var i, s;
    if (this.mDataChannel == null) return !1;
    const e = (i = this.mDataChannel) == null ? void 0 : i.connectStatus, t = ((s = this.mDataChannel) == null ? void 0 : s.dataChannelOpened) ?? !1;
    return e == _t.connected && t;
  }
  isConnecting() {
    var t;
    const e = (t = this.mDataChannel) == null ? void 0 : t.connectStatus;
    return !e || e == _t.connecting || e == _t.new;
  }
  async checkThingProperties() {
    if (!Object.keys(this.deviceInfo.thingProperties).length)
      try {
        const e = await fd(this.deviceInfo.iotId);
        this.deviceInfo.thingProperties = e;
      } catch (e) {
        S.e(this.TAG, `${this.getChannelMode()} checkThingProperties error`, e);
      }
  }
  getChannelMode() {
    var t;
    const e = ((t = this.mDataChannel) == null ? void 0 : t.channelMode) ?? yt.NONE;
    return yt[e];
  }
  onDataChannelStatusChanged(e) {
    var t;
    S.i(this.TAG, `${this.getChannelMode()} onDataChannelStatusChanged status=${ci[e]}`), this.mDataChannelState = e, (t = this.mOnDataChannelListener) == null || t.onStatusChange(e);
  }
  releaseChannel(e) {
    var i;
    S.i(this.TAG, `${this.getChannelMode()} release data , ignoreStatus = ${e}`);
    const t = this.mDataChannel;
    t != null && (t.removeListener(Ge.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.onRTCConnectStateChanged), t.removeListener(Ge.WEBRTC_ON_DATA_CHANNEL_OPEN, this.onChannelOpen), t.removeListener(Ge.WEBRTC_ON_DATA_CHANNEL_ERR, this.onChannelError), t.removeListener(Ge.WEBRTC_ON_DATA_CHANNEL_MSG, this.onChannelMessage), t6(t), t.dataChannelParentCount <= 0 && ((i = this.signalingProxy) == null || i.notifyDeviceDestroyChannel(this.datachannelStreamName)), this.mDataChannel = void 0), e || this.onDataChannelStatusChanged(ci.STATE_IDLE), S.i(this.TAG, "destroy data channel completed");
  }
  /**
   * 信令 buffer 协议定义：https://xiangsutech.feishu.cn/wiki/OdJHwsLoZieHLzktaGDctkg3nfB
   *
   * @param cmdId
   * @param binary - 二进制
   * @param jsonInfo - 扩展json
   * @returns
   */
  getSendBuffer(e, t, i) {
    S.d(this.TAG, `get signaling send msg cmdId=${e}`);
    const s = new Uint8Array(9), n = new DataView(s.buffer), a = (i == null ? void 0 : i.length) ?? 0;
    n.setUint16(0, a + 9, !1), n.setUint8(2, ns.ROUTE_C2C), n.setUint16(3, e, !1);
    const o = (t == null ? void 0 : t.length) ?? 0;
    n.setUint32(5, o, !1);
    const c = new Uint8Array(0);
    return ui(s, i ?? c, t ?? c).buffer;
  }
  sendSigCmdData(e, t, i, s, n, a) {
    var h;
    let o;
    if (i != null) {
      const u = JSON.stringify(i);
      o = ri.string2Unit8Array(u);
    }
    const c = this.getSendBuffer(e, t, o), l = 64 * 1024;
    let d = 0;
    for (; d < c.byteLength; ) {
      const u = c.slice(d, d + l);
      (h = this.mDataChannel) == null || h.sendDataChannelMessage(u), d += l;
    }
    if (n && a && i) {
      const u = i.method + i.id;
      S.d(this.TAG, "sendMessageCallback eventKey=${eventKey} timeoutMs=$timeoutMs");
      const f = (...m) => {
        const g = m.length ? m[0] : void 0, x = m.length > 1 ? m[1] : void 0, _ = {
          signallingRsp: g,
          body: x ?? new Uint8Array(0)
        };
        this.sendMessageCallbackKeys.delete(u), n(_);
      }, p = setTimeout(() => {
        this.sendMessageCallbackKeys.delete(u), this.mEventEmitter.off(u, f);
        const m = new pt(ki.DataChannelRspTimeout, "datachannel rsp timeout");
        a == null || a(m);
      }, s);
      this.sendMessageCallbackKeys.set(u, p), this.mEventEmitter.once(u, f);
    }
  }
};
y(fo, "DEFAULT_RETRY_MAX", 1);
let Jc = fo;
class lh {
  /**
   * dataChannel 公共业务
   *
   * @param deviceInfo - 设备信息
   * @param sendControlInternal - 发送信令频率控制
   */
  constructor(e, t = 0) {
    y(this, "TAG", "BusinessDataChannel");
    y(this, "deviceInfo");
    y(this, "sendControlInternal");
    y(this, "dataChannel");
    y(this, "mOnDataChannelListener");
    y(this, "mWaitQueue", []);
    y(this, "sendContrlTimer", 0);
    y(this, "lastSendTime", 0);
    y(this, "sendControlQueue", []);
    y(this, "checkSendQueue", () => {
      var e, t;
      if (!(this.sendControlQueue.length < 1)) {
        if (this.isValidChannel()) {
          const i = Date.now();
          if (i - this.lastSendTime > this.sendControlInternal) {
            this.lastSendTime = i;
            const s = this.sendControlQueue.shift();
            s && (S.i(this.TAG, `realSendCmdData ${s == null ? void 0 : s.cmdId} ${JSON.stringify(s == null ? void 0 : s.reqParams)} ${(e = s == null ? void 0 : s.data) == null ? void 0 : e.length}`), (t = this.dataChannel) == null || t.sendSigCmdData(s.cmdId, s.data, s.reqParams, s.timeoutMs, s.resolve, s.reject));
          }
        }
        this.sendContrlTimer = setTimeout(this.checkSendQueue, this.sendControlInternal);
      }
    });
    this.deviceInfo = e, this.sendControlInternal = t;
  }
  createChannel() {
    let e = this.dataChannel;
    e && !e.isValidChannel() && !e.isConnecting() && this.destroyChannel(), e == null && (e = this.dataChannel = new Jc(this.deviceInfo), e == null || e.setOnDataChannelListener(this));
  }
  destroyChannel() {
    var e;
    S.d(this.TAG, "destroyChannel"), (e = this.dataChannel) == null || e.destroy(), this.dataChannel = void 0;
  }
  on(e, t) {
    var i;
    (i = this.dataChannel) == null || i.on(e, t);
  }
  off(e, t) {
    var i;
    (i = this.dataChannel) == null || i.off(e, t);
  }
  sendSigCmdData(e, t, i, s) {
    return new Promise((n, a) => {
      var c;
      const o = {
        cmdId: e,
        reqParams: t,
        resolve: n,
        reject: a,
        timeoutMs: s,
        data: i
      };
      this.sendControlQueue.push(o), (c = this.dataChannel) != null && c.isValidChannel() ? (S.i(this.TAG, `sendCmdData ${e} ${JSON.stringify(t)} ${i == null ? void 0 : i.length}`), this.checkSendQueue()) : (S.d(this.TAG, `sendCmdData wait connect ${e} ${t == null ? void 0 : t.id} ${i == null ? void 0 : i.length}`), this.createChannel());
    });
  }
  /**
   * 发送自定义数据
   *
   * @param cmdId - 指令，取值需要在0到1000
   * @param data - 二进制数据 最大128KB
   */
  sendCmdData(e, t) {
    if (S.d(this.TAG, `sendCmdData cmdId=${e} size=${t == null ? void 0 : t.length}`), e < 0 || e > 1e3) throw new pt(ki.DataChannelCmdIdError, "cmd id must be in [0, 1000]");
    if (t && t.length > 128 * 1024) throw new pt(ki.DataChannelDataSizeError, "data size must be less than 128KB");
    this.sendSigCmdData(e, void 0, t);
  }
  /**
   * 销毁通道
   */
  destroy() {
    S.i(this.TAG, "destroy"), this.destroyChannel(), this.sendControlQueue.length = 0, this.mWaitQueue.length = 0, clearTimeout(this.sendContrlTimer);
  }
  /**
   * 是否支持DataChannel
   * @returns
   */
  static isSupport(e) {
    return e.supportSdkAbility(Ir.SDK_ABILITY_DATA_CHANNEL);
  }
  /**
   * 是否支持DataChannel
   * @returns
   */
  isSupport() {
    return lh.isSupport(this.deviceInfo);
  }
  /**
   * 当前通道是否有效
   * @returns
   */
  isValidChannel() {
    var e;
    return ((e = this.dataChannel) == null ? void 0 : e.isValidChannel()) == !0;
  }
  /**
   * 当前通道是否正在连接中
   * @returns
   */
  isConnecting() {
    var e;
    return ((e = this.dataChannel) == null ? void 0 : e.isConnecting()) == !0;
  }
  /**
   * 设置监听
   *
   * @param onDataChannelListener - 监听回调
   */
  setOnDataChannelListener(e) {
    this.mOnDataChannelListener = e, this.createChannel();
  }
  onStatusChange(e) {
    var t;
    if (this.mOnDataChannelListener) {
      (t = this.mOnDataChannelListener) == null || t.onStatusChange(e);
      return;
    }
    switch (e) {
      case ci.STATE_SUCCESS: {
        this.sendControlQueue.push(...this.mWaitQueue), this.mWaitQueue.length = 0, this.checkSendQueue();
        break;
      }
      case ci.STATE_ERROR:
        this.destroyChannel(), this.mWaitQueue.forEach((i) => {
          var s;
          (s = i.reject) == null || s.call(i, new pt(ki.DataChannelInvalid, "data channel invalid"));
        }), this.mWaitQueue.length = 0;
    }
  }
  onData(e, t) {
    var i;
    (i = this.mOnDataChannelListener) == null || i.onData(e, t);
  }
}
class B6 extends lh {
  /**
   * 
   * @param deviceInfo -设备信息
   */
  constructor(e) {
    super(e);
  }
  getSigRequest(e) {
    const t = this.deviceInfo, i = yy.GET_SDCARD_PIC;
    return Ks(i, e, {
      ack: 1
    }, t.productKey, t.deviceName, 0);
  }
  async getPicture(e, t) {
    var c;
    const i = {
      PicIds: [e]
    }, s = this.getSigRequest(i), n = await this.sendSigCmdData(_y.GET_SDCARD_PIC, s, void 0, t), a = (c = n.signallingRsp) == null ? void 0 : c.data;
    return a != null && a.PicSize ? new Blob([n.body.buffer], { type: "application/octet-stream" }) : Promise.reject(new pt(ki.DataChannelGetSDCardPicError, "get sdcard picture failed"));
  }
}
export {
  y6 as RTCXAccount,
  _6 as RTCXAccountTypes,
  v6 as RTCXCloudPlayback,
  c6 as RTCXCommonTypes,
  lh as RTCXDataChannel,
  M6 as RTCXDataChannelTypes,
  f6 as RTCXDeviceMgr,
  u6 as RTCXDeviceMgrTypes,
  x6 as RTCXDeviceShareMgr,
  p6 as RTCXDeviceWakeUpMgr,
  E6 as RTCXPlaybackTypes,
  B6 as RTCXSDCardPictureGetter,
  d6 as RTCXSDCardPlayback,
  g6 as RTCXSDKInit,
  m6 as RTCXSDKInitTypes,
  S6 as RTCXSignalingTypes,
  w6 as RTCXThingModelPanel,
  h6 as RTCXThingModelTypes,
  gy as RTCXWebPlayer,
  T6 as RTCXWebPlayerTypes
};
