UNPKG

@hakit/components

Version:
14,427 lines 495 kB
const B = Number.isFinite || function(n) {
  return typeof n == "number" && isFinite(n);
}, or = Number.isSafeInteger || function(n) {
  return typeof n == "number" && Math.abs(n) <= lr;
}, lr = Number.MAX_SAFE_INTEGER || 9007199254740991;
let Y = /* @__PURE__ */ (function(n) {
  return n.NETWORK_ERROR = "networkError", n.MEDIA_ERROR = "mediaError", n.KEY_SYSTEM_ERROR = "keySystemError", n.MUX_ERROR = "muxError", n.OTHER_ERROR = "otherError", n;
})({}), D = /* @__PURE__ */ (function(n) {
  return n.KEY_SYSTEM_NO_KEYS = "keySystemNoKeys", n.KEY_SYSTEM_NO_ACCESS = "keySystemNoAccess", n.KEY_SYSTEM_NO_SESSION = "keySystemNoSession", n.KEY_SYSTEM_NO_CONFIGURED_LICENSE = "keySystemNoConfiguredLicense", n.KEY_SYSTEM_LICENSE_REQUEST_FAILED = "keySystemLicenseRequestFailed", n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED = "keySystemServerCertificateRequestFailed", n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED = "keySystemServerCertificateUpdateFailed", n.KEY_SYSTEM_SESSION_UPDATE_FAILED = "keySystemSessionUpdateFailed", n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED = "keySystemStatusOutputRestricted", n.KEY_SYSTEM_STATUS_INTERNAL_ERROR = "keySystemStatusInternalError", n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR = "keySystemDestroyMediaKeysError", n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR = "keySystemDestroyCloseSessionError", n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR = "keySystemDestroyRemoveSessionError", n.MANIFEST_LOAD_ERROR = "manifestLoadError", n.MANIFEST_LOAD_TIMEOUT = "manifestLoadTimeOut", n.MANIFEST_PARSING_ERROR = "manifestParsingError", n.MANIFEST_INCOMPATIBLE_CODECS_ERROR = "manifestIncompatibleCodecsError", n.LEVEL_EMPTY_ERROR = "levelEmptyError", n.LEVEL_LOAD_ERROR = "levelLoadError", n.LEVEL_LOAD_TIMEOUT = "levelLoadTimeOut", n.LEVEL_PARSING_ERROR = "levelParsingError", n.LEVEL_SWITCH_ERROR = "levelSwitchError", n.AUDIO_TRACK_LOAD_ERROR = "audioTrackLoadError", n.AUDIO_TRACK_LOAD_TIMEOUT = "audioTrackLoadTimeOut", n.SUBTITLE_LOAD_ERROR = "subtitleTrackLoadError", n.SUBTITLE_TRACK_LOAD_TIMEOUT = "subtitleTrackLoadTimeOut", n.FRAG_LOAD_ERROR = "fragLoadError", n.FRAG_LOAD_TIMEOUT = "fragLoadTimeOut", n.FRAG_DECRYPT_ERROR = "fragDecryptError", n.FRAG_PARSING_ERROR = "fragParsingError", n.FRAG_GAP = "fragGap", n.REMUX_ALLOC_ERROR = "remuxAllocError", n.KEY_LOAD_ERROR = "keyLoadError", n.KEY_LOAD_TIMEOUT = "keyLoadTimeOut", n.BUFFER_ADD_CODEC_ERROR = "bufferAddCodecError", n.BUFFER_INCOMPATIBLE_CODECS_ERROR = "bufferIncompatibleCodecsError", n.BUFFER_APPEND_ERROR = "bufferAppendError", n.BUFFER_APPENDING_ERROR = "bufferAppendingError", n.BUFFER_STALLED_ERROR = "bufferStalledError", n.BUFFER_FULL_ERROR = "bufferFullError", n.BUFFER_SEEK_OVER_HOLE = "bufferSeekOverHole", n.BUFFER_NUDGE_ON_STALL = "bufferNudgeOnStall", n.ASSET_LIST_LOAD_ERROR = "assetListLoadError", n.ASSET_LIST_LOAD_TIMEOUT = "assetListLoadTimeout", n.ASSET_LIST_PARSING_ERROR = "assetListParsingError", n.INTERSTITIAL_ASSET_ITEM_ERROR = "interstitialAssetItemError", n.INTERNAL_EXCEPTION = "internalException", n.INTERNAL_ABORTED = "aborted", n.ATTACH_MEDIA_ERROR = "attachMediaError", n.UNKNOWN = "unknown", n;
})({}), E = /* @__PURE__ */ (function(n) {
  return n.MEDIA_ATTACHING = "hlsMediaAttaching", n.MEDIA_ATTACHED = "hlsMediaAttached", n.MEDIA_DETACHING = "hlsMediaDetaching", n.MEDIA_DETACHED = "hlsMediaDetached", n.MEDIA_ENDED = "hlsMediaEnded", n.STALL_RESOLVED = "hlsStallResolved", n.BUFFER_RESET = "hlsBufferReset", n.BUFFER_CODECS = "hlsBufferCodecs", n.BUFFER_CREATED = "hlsBufferCreated", n.BUFFER_APPENDING = "hlsBufferAppending", n.BUFFER_APPENDED = "hlsBufferAppended", n.BUFFER_EOS = "hlsBufferEos", n.BUFFERED_TO_END = "hlsBufferedToEnd", n.BUFFER_FLUSHING = "hlsBufferFlushing", n.BUFFER_FLUSHED = "hlsBufferFlushed", n.MANIFEST_LOADING = "hlsManifestLoading", n.MANIFEST_LOADED = "hlsManifestLoaded", n.MANIFEST_PARSED = "hlsManifestParsed", n.LEVEL_SWITCHING = "hlsLevelSwitching", n.LEVEL_SWITCHED = "hlsLevelSwitched", n.LEVEL_LOADING = "hlsLevelLoading", n.LEVEL_LOADED = "hlsLevelLoaded", n.LEVEL_UPDATED = "hlsLevelUpdated", n.LEVEL_PTS_UPDATED = "hlsLevelPtsUpdated", n.LEVELS_UPDATED = "hlsLevelsUpdated", n.AUDIO_TRACKS_UPDATED = "hlsAudioTracksUpdated", n.AUDIO_TRACK_SWITCHING = "hlsAudioTrackSwitching", n.AUDIO_TRACK_SWITCHED = "hlsAudioTrackSwitched", n.AUDIO_TRACK_LOADING = "hlsAudioTrackLoading", n.AUDIO_TRACK_LOADED = "hlsAudioTrackLoaded", n.AUDIO_TRACK_UPDATED = "hlsAudioTrackUpdated", n.SUBTITLE_TRACKS_UPDATED = "hlsSubtitleTracksUpdated", n.SUBTITLE_TRACKS_CLEARED = "hlsSubtitleTracksCleared", n.SUBTITLE_TRACK_SWITCH = "hlsSubtitleTrackSwitch", n.SUBTITLE_TRACK_LOADING = "hlsSubtitleTrackLoading", n.SUBTITLE_TRACK_LOADED = "hlsSubtitleTrackLoaded", n.SUBTITLE_TRACK_UPDATED = "hlsSubtitleTrackUpdated", n.SUBTITLE_FRAG_PROCESSED = "hlsSubtitleFragProcessed", n.CUES_PARSED = "hlsCuesParsed", n.NON_NATIVE_TEXT_TRACKS_FOUND = "hlsNonNativeTextTracksFound", n.INIT_PTS_FOUND = "hlsInitPtsFound", n.FRAG_LOADING = "hlsFragLoading", n.FRAG_LOAD_EMERGENCY_ABORTED = "hlsFragLoadEmergencyAborted", n.FRAG_LOADED = "hlsFragLoaded", n.FRAG_DECRYPTED = "hlsFragDecrypted", n.FRAG_PARSING_INIT_SEGMENT = "hlsFragParsingInitSegment", n.FRAG_PARSING_USERDATA = "hlsFragParsingUserdata", n.FRAG_PARSING_METADATA = "hlsFragParsingMetadata", n.FRAG_PARSED = "hlsFragParsed", n.FRAG_BUFFERED = "hlsFragBuffered", n.FRAG_CHANGED = "hlsFragChanged", n.FPS_DROP = "hlsFpsDrop", n.FPS_DROP_LEVEL_CAPPING = "hlsFpsDropLevelCapping", n.MAX_AUTO_LEVEL_UPDATED = "hlsMaxAutoLevelUpdated", n.ERROR = "hlsError", n.DESTROYING = "hlsDestroying", n.KEY_LOADING = "hlsKeyLoading", n.KEY_LOADED = "hlsKeyLoaded", n.LIVE_BACK_BUFFER_REACHED = "hlsLiveBackBufferReached", n.BACK_BUFFER_REACHED = "hlsBackBufferReached", n.STEERING_MANIFEST_LOADED = "hlsSteeringManifestLoaded", n.ASSET_LIST_LOADING = "hlsAssetListLoading", n.ASSET_LIST_LOADED = "hlsAssetListLoaded", n.INTERSTITIALS_UPDATED = "hlsInterstitialsUpdated", n.INTERSTITIALS_BUFFERED_TO_BOUNDARY = "hlsInterstitialsBufferedToBoundary", n.INTERSTITIAL_ASSET_PLAYER_CREATED = "hlsInterstitialAssetPlayerCreated", n.INTERSTITIAL_STARTED = "hlsInterstitialStarted", n.INTERSTITIAL_ASSET_STARTED = "hlsInterstitialAssetStarted", n.INTERSTITIAL_ASSET_ENDED = "hlsInterstitialAssetEnded", n.INTERSTITIAL_ASSET_ERROR = "hlsInterstitialAssetError", n.INTERSTITIAL_ENDED = "hlsInterstitialEnded", n.INTERSTITIALS_PRIMARY_RESUMED = "hlsInterstitialsPrimaryResumed", n.PLAYOUT_LIMIT_REACHED = "hlsPlayoutLimitReached", n.EVENT_CUE_ENTER = "hlsEventCueEnter", n;
})({});
var X = {
  MANIFEST: "manifest",
  LEVEL: "level",
  AUDIO_TRACK: "audioTrack",
  SUBTITLE_TRACK: "subtitleTrack"
}, W = {
  MAIN: "main",
  AUDIO: "audio",
  SUBTITLE: "subtitle"
};
class Nt {
  //  About half of the estimated value will be from the last |halfLife| samples by weight.
  constructor(t, e = 0, i = 0) {
    this.halfLife = void 0, this.alpha_ = void 0, this.estimate_ = void 0, this.totalWeight_ = void 0, this.halfLife = t, this.alpha_ = t ? Math.exp(Math.log(0.5) / t) : 0, this.estimate_ = e, this.totalWeight_ = i;
  }
  sample(t, e) {
    const i = Math.pow(this.alpha_, t);
    this.estimate_ = e * (1 - i) + i * this.estimate_, this.totalWeight_ += t;
  }
  getTotalWeight() {
    return this.totalWeight_;
  }
  getEstimate() {
    if (this.alpha_) {
      const t = 1 - Math.pow(this.alpha_, this.totalWeight_);
      if (t)
        return this.estimate_ / t;
    }
    return this.estimate_;
  }
}
class ur {
  constructor(t, e, 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 Nt(t), this.fast_ = new Nt(e), this.defaultTTFB_ = s, this.ttfb_ = new Nt(t);
  }
  update(t, e) {
    const {
      slow_: i,
      fast_: s,
      ttfb_: r
    } = this;
    i.halfLife !== t && (this.slow_ = new Nt(t, i.getEstimate(), i.getTotalWeight())), s.halfLife !== e && (this.fast_ = new Nt(e, s.getEstimate(), s.getTotalWeight())), r.halfLife !== t && (this.ttfb_ = new Nt(t, r.getEstimate(), r.getTotalWeight()));
  }
  sample(t, e) {
    t = Math.max(t, this.minDelayMs_);
    const i = 8 * e, s = t / 1e3, r = i / s;
    this.fast_.sample(s, r), this.slow_.sample(s, r);
  }
  sampleTTFB(t) {
    const e = t / 1e3, i = Math.sqrt(2) * Math.exp(-Math.pow(e, 2) / 2);
    this.ttfb_.sample(i, Math.max(t, 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 dr(n, t, e) {
  return (t = cr(t)) in n ? Object.defineProperty(n, t, {
    value: e,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : n[t] = e, n;
}
function nt() {
  return nt = Object.assign ? Object.assign.bind() : function(n) {
    for (var t = 1; t < arguments.length; t++) {
      var e = arguments[t];
      for (var i in e) ({}).hasOwnProperty.call(e, i) && (n[i] = e[i]);
    }
    return n;
  }, nt.apply(null, arguments);
}
function ni(n, t) {
  var e = Object.keys(n);
  if (Object.getOwnPropertySymbols) {
    var i = Object.getOwnPropertySymbols(n);
    t && (i = i.filter(function(s) {
      return Object.getOwnPropertyDescriptor(n, s).enumerable;
    })), e.push.apply(e, i);
  }
  return e;
}
function ct(n) {
  for (var t = 1; t < arguments.length; t++) {
    var e = arguments[t] != null ? arguments[t] : {};
    t % 2 ? ni(Object(e), !0).forEach(function(i) {
      dr(n, i, e[i]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n, Object.getOwnPropertyDescriptors(e)) : ni(Object(e)).forEach(function(i) {
      Object.defineProperty(n, i, Object.getOwnPropertyDescriptor(e, i));
    });
  }
  return n;
}
function hr(n, t) {
  if (typeof n != "object" || !n) return n;
  var e = n[Symbol.toPrimitive];
  if (e !== void 0) {
    var i = e.call(n, t);
    if (typeof i != "object") return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (t === "string" ? String : Number)(n);
}
function cr(n) {
  var t = hr(n, "string");
  return typeof t == "symbol" ? t : t + "";
}
class Rt {
  constructor(t, e) {
    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 = `[${t}]:`;
    this.trace = It, this.debug = e.debug.bind(null, i), this.log = e.log.bind(null, i), this.warn = e.warn.bind(null, i), this.info = e.info.bind(null, i), this.error = e.error.bind(null, i);
  }
}
const It = function() {
}, fr = {
  trace: It,
  debug: It,
  log: It,
  warn: It,
  info: It,
  error: It
};
function Be() {
  return nt({}, fr);
}
function gr(n, t) {
  const e = self.console[n];
  return e ? e.bind(self.console, `${t ? "[" + t + "] " : ""}[${n}] >`) : It;
}
function ai(n, t, e) {
  return t[n] ? t[n].bind(t) : gr(n, e);
}
const $e = Be();
function mr(n, t, e) {
  const i = Be();
  if (typeof console == "object" && n === !0 || typeof n == "object") {
    const s = [
      // Remove out from list here to hard-disable a log-level
      // 'trace',
      "debug",
      "log",
      "info",
      "warn",
      "error"
    ];
    s.forEach((r) => {
      i[r] = ai(r, n, e);
    });
    try {
      i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.13`);
    } catch {
      return Be();
    }
    s.forEach((r) => {
      $e[r] = ai(r, n);
    });
  } else
    nt($e, i);
  return i;
}
const J = $e;
function ls(n) {
  return n && n.__esModule && Object.prototype.hasOwnProperty.call(n, "default") ? n.default : n;
}
var xe, oi;
function pr() {
  return oi || (oi = 1, xe = {}), xe;
}
var Ft = pr(), Er = /* @__PURE__ */ ls(Ft);
function _t(n = !0) {
  return typeof self > "u" ? void 0 : (n || !self.MediaSource) && self.ManagedMediaSource || self.MediaSource || self.WebKitMediaSource;
}
function vr(n) {
  return typeof self < "u" && n === self.ManagedMediaSource;
}
function yr(n, t) {
  const e = Object.keys(n), i = Object.keys(t), s = e.length, r = i.length;
  return !s || !r || s === r && !e.some((a) => i.indexOf(a) === -1);
}
function gt(n, t = !1) {
  if (typeof TextDecoder < "u") {
    const l = new TextDecoder("utf-8").decode(n);
    if (t) {
      const d = l.indexOf("\0");
      return d !== -1 ? l.substring(0, d) : l;
    }
    return l.replace(/\0/g, "");
  }
  const e = n.length;
  let i, s, r, a = "", o = 0;
  for (; o < e; ) {
    if (i = n[o++], i === 0 && t)
      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 = n[o++], a += String.fromCharCode((i & 31) << 6 | s & 63);
        break;
      case 14:
        s = n[o++], r = n[o++], a += String.fromCharCode((i & 15) << 12 | (s & 63) << 6 | (r & 63) << 0);
        break;
    }
  }
  return a;
}
function qt(n) {
  let t = "";
  for (let e = 0; e < n.length; e++) {
    let i = n[e].toString(16);
    i.length < 2 && (i = "0" + i), t += i;
  }
  return t;
}
function us(n) {
  return Uint8Array.from(n.replace(/^0x/, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")).buffer;
}
var Se = { exports: {} }, li;
function Tr() {
  return li || (li = 1, (function(n, t) {
    (function(e) {
      var i = /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/, s = /^(?=([^\/?#]*))\1([^]*)$/, r = /(?:\/|^)\.(?=\/)/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(u, l, d) {
          if (d = d || {}, u = u.trim(), l = l.trim(), !l) {
            if (!d.alwaysNormalize)
              return u;
            var h = o.parseURL(u);
            if (!h)
              throw new Error("Error trying to parse base URL.");
            return h.path = o.normalizePath(
              h.path
            ), o.buildURLFromParts(h);
          }
          var c = o.parseURL(l);
          if (!c)
            throw new Error("Error trying to parse relative URL.");
          if (c.scheme)
            return d.alwaysNormalize ? (c.path = o.normalizePath(c.path), o.buildURLFromParts(c)) : l;
          var f = o.parseURL(u);
          if (!f)
            throw new Error("Error trying to parse base URL.");
          if (!f.netLoc && f.path && f.path[0] !== "/") {
            var g = s.exec(f.path);
            f.netLoc = g[1], f.path = g[2];
          }
          f.netLoc && !f.path && (f.path = "/");
          var p = {
            // 2c) Otherwise, the embedded URL inherits the scheme of
            // the base URL.
            scheme: f.scheme,
            netLoc: c.netLoc,
            path: null,
            params: c.params,
            query: c.query,
            fragment: c.fragment
          };
          if (!c.netLoc && (p.netLoc = f.netLoc, c.path[0] !== "/"))
            if (!c.path)
              p.path = f.path, c.params || (p.params = f.params, c.query || (p.query = f.query));
            else {
              var m = f.path, y = m.substring(0, m.lastIndexOf("/") + 1) + c.path;
              p.path = o.normalizePath(y);
            }
          return p.path === null && (p.path = d.alwaysNormalize ? o.normalizePath(c.path) : c.path), o.buildURLFromParts(p);
        },
        parseURL: function(u) {
          var l = i.exec(u);
          return l ? {
            scheme: l[1] || "",
            netLoc: l[2] || "",
            path: l[3] || "",
            params: l[4] || "",
            query: l[5] || "",
            fragment: l[6] || ""
          } : null;
        },
        normalizePath: function(u) {
          for (u = u.split("").reverse().join("").replace(r, ""); u.length !== (u = u.replace(a, "")).length; )
            ;
          return u.split("").reverse().join("");
        },
        buildURLFromParts: function(u) {
          return u.scheme + u.netLoc + u.path + u.params + u.query + u.fragment;
        }
      };
      n.exports = o;
    })();
  })(Se)), Se.exports;
}
var je = Tr();
class qe {
  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 tt = {
  AUDIO: "audio",
  VIDEO: "video",
  AUDIOVIDEO: "audiovideo"
};
class ds {
  constructor(t) {
    this._byteRange = null, this._url = null, this._stats = null, this._streams = null, this.base = void 0, this.relurl = void 0, typeof t == "string" && (t = {
      url: t
    }), this.base = t, Sr(this, "stats");
  }
  // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  setByteRange(t, e) {
    const i = t.split("@", 2);
    let s;
    i.length === 1 ? s = e?.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 = {
      [tt.AUDIO]: null,
      [tt.VIDEO]: null,
      [tt.AUDIOVIDEO]: null
    }), this._streams;
  }
  set elementaryStreams(t) {
    this._streams = t;
  }
  get hasStats() {
    return this._stats !== null;
  }
  get hasStreams() {
    return this._streams !== null;
  }
  get stats() {
    return this._stats === null && (this._stats = new qe()), this._stats;
  }
  set stats(t) {
    this._stats = t;
  }
  get url() {
    return !this._url && this.baseurl && this.relurl && (this._url = je.buildAbsoluteURL(this.baseurl, this.relurl, {
      alwaysNormalize: !0
    })), this._url || "";
  }
  set url(t) {
    this._url = t;
  }
  clearElementaryStreamInfo() {
    const {
      elementaryStreams: t
    } = this;
    t[tt.AUDIO] = null, t[tt.VIDEO] = null, t[tt.AUDIOVIDEO] = null;
  }
}
function ft(n) {
  return n.sn !== "initSegment";
}
class Le extends ds {
  constructor(t, e) {
    super(e), 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 = t;
  }
  get byteLength() {
    if (this.hasStats) {
      const t = this.stats.total;
      if (t)
        return t;
    }
    if (this.byteRange.length) {
      const t = this.byteRange[0], e = this.byteRange[1];
      if (B(t) && B(e))
        return e - t;
    }
    return null;
  }
  get bitrate() {
    return this.byteLength ? this.byteLength * 8 / this.duration : this._bitrate ? this._bitrate : null;
  }
  set bitrate(t) {
    this._bitrate = t;
  }
  get decryptdata() {
    var t;
    const {
      levelkeys: e
    } = this;
    if (!e || e.NONE)
      return null;
    if (e.identity)
      this._decryptdata || (this._decryptdata = e.identity.getDecryptData(this.sn));
    else if (!((t = this._decryptdata) != null && t.keyId)) {
      const i = Object.keys(e);
      if (i.length === 1) {
        const s = this._decryptdata = e[i[0]] || null;
        s && (this._decryptdata = s.getDecryptData(this.sn, e));
      }
    }
    return this._decryptdata;
  }
  get end() {
    return this.start + this.duration;
  }
  get endProgramDateTime() {
    if (this.programDateTime === null)
      return null;
    const t = B(this.duration) ? this.duration : 0;
    return this.programDateTime + t * 1e3;
  }
  get encrypted() {
    var t;
    if ((t = this._decryptdata) != null && t.encrypted)
      return !0;
    if (this.levelkeys) {
      var e;
      const i = Object.keys(this.levelkeys), s = i.length;
      if (s > 1 || s === 1 && (e = this.levelkeys[i[0]]) != null && e.encrypted)
        return !0;
    }
    return !1;
  }
  get programDateTime() {
    return this._programDateTime === null && this.rawProgramDateTime && (this.programDateTime = Date.parse(this.rawProgramDateTime)), this._programDateTime;
  }
  set programDateTime(t) {
    if (!B(t)) {
      this._programDateTime = this.rawProgramDateTime = null;
      return;
    }
    this._programDateTime = t;
  }
  get ref() {
    return ft(this) ? (this._ref || (this._ref = {
      base: this.base,
      start: this.start,
      duration: this.duration,
      sn: this.sn,
      programDateTime: this.programDateTime
    }), this._ref) : null;
  }
  addStart(t) {
    this.setStart(this.start + t);
  }
  setStart(t) {
    this.start = t, this._ref && (this._ref.start = t);
  }
  setDuration(t) {
    this.duration = t, this._ref && (this._ref.duration = t);
  }
  setKeyFormat(t) {
    const e = this.levelkeys;
    if (e) {
      var i;
      const s = e[t];
      s && !((i = this._decryptdata) != null && i.keyId) && (this._decryptdata = s.getDecryptData(this.sn, e));
    }
  }
  abortRequests() {
    var t, e;
    (t = this.loader) == null || t.abort(), (e = this.keyLoader) == null || e.abort();
  }
  setElementaryStreamInfo(t, e, i, s, r, a = !1) {
    const {
      elementaryStreams: o
    } = this, u = o[t];
    if (!u) {
      o[t] = {
        startPTS: e,
        endPTS: i,
        startDTS: s,
        endDTS: r,
        partial: a
      };
      return;
    }
    u.startPTS = Math.min(u.startPTS, e), u.endPTS = Math.max(u.endPTS, i), u.startDTS = Math.min(u.startDTS, s), u.endDTS = Math.max(u.endDTS, r);
  }
}
class xr extends ds {
  constructor(t, e, i, s, r) {
    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 = t.decimalFloatingPoint("DURATION"), this.gap = t.bool("GAP"), this.independent = t.bool("INDEPENDENT"), this.relurl = t.enumeratedString("URI"), this.fragment = e, this.index = s;
    const a = t.enumeratedString("BYTERANGE");
    a && this.setByteRange(a, r), r && (this.fragOffset = r.fragOffset + r.duration);
  }
  get start() {
    return this.fragment.start + this.fragOffset;
  }
  get end() {
    return this.start + this.duration;
  }
  get loaded() {
    const {
      elementaryStreams: t
    } = this;
    return !!(t.audio || t.video || t.audiovideo);
  }
}
function hs(n, t) {
  const e = Object.getPrototypeOf(n);
  if (e) {
    const i = Object.getOwnPropertyDescriptor(e, t);
    return i || hs(e, t);
  }
}
function Sr(n, t) {
  const e = hs(n, t);
  e && (e.enumerable = !0, Object.defineProperty(n, t, e));
}
const ui = Math.pow(2, 32) - 1, Lr = [].push, cs = {
  video: 1,
  audio: 2,
  id3: 3,
  text: 4
};
function rt(n) {
  return String.fromCharCode.apply(null, n);
}
function fs(n, t) {
  const e = n[t] << 8 | n[t + 1];
  return e < 0 ? 65536 + e : e;
}
function K(n, t) {
  const e = gs(n, t);
  return e < 0 ? 4294967296 + e : e;
}
function di(n, t) {
  let e = K(n, t);
  return e *= Math.pow(2, 32), e += K(n, t + 4), e;
}
function gs(n, t) {
  return n[t] << 24 | n[t + 1] << 16 | n[t + 2] << 8 | n[t + 3];
}
function Ar(n) {
  const t = n.byteLength;
  for (let e = 0; e < t; ) {
    const i = K(n, e);
    if (i > 8 && n[e + 4] === 109 && n[e + 5] === 111 && n[e + 6] === 111 && n[e + 7] === 102)
      return !0;
    e = i > 1 ? e + i : t;
  }
  return !1;
}
function j(n, t) {
  const e = [];
  if (!t.length)
    return e;
  const i = n.byteLength;
  for (let s = 0; s < i; ) {
    const r = K(n, s), a = rt(n.subarray(s + 4, s + 8)), o = r > 1 ? s + r : i;
    if (a === t[0])
      if (t.length === 1)
        e.push(n.subarray(s + 8, o));
      else {
        const u = j(n.subarray(s + 8, o), t.slice(1));
        u.length && Lr.apply(e, u);
      }
    s = o;
  }
  return e;
}
function Rr(n) {
  const t = [], e = n[0];
  let i = 8;
  const s = K(n, i);
  i += 4;
  let r = 0, a = 0;
  e === 0 ? (r = K(n, i), a = K(n, i + 4), i += 8) : (r = di(n, i), a = di(n, i + 8), i += 16), i += 2;
  let o = n.length + a;
  const u = fs(n, i);
  i += 2;
  for (let l = 0; l < u; l++) {
    let d = i;
    const h = K(n, d);
    d += 4;
    const c = h & 2147483647;
    if ((h & 2147483648) >>> 31 === 1)
      return J.warn("SIDX has hierarchical references (not supported)"), null;
    const g = K(n, d);
    d += 4, t.push({
      referenceSize: c,
      subsegmentDuration: g,
      // unscaled
      info: {
        duration: g / s,
        start: o,
        end: o + c - 1
      }
    }), o += c, d += 4, i = d;
  }
  return {
    earliestPresentationTime: r,
    timescale: s,
    version: e,
    referencesCount: u,
    references: t
  };
}
function ms(n) {
  const t = [], e = j(n, ["moov", "trak"]);
  for (let s = 0; s < e.length; s++) {
    const r = e[s], a = j(r, ["tkhd"])[0];
    if (a) {
      let o = a[0];
      const u = K(a, o === 0 ? 12 : 20), l = j(r, ["mdia", "mdhd"])[0];
      if (l) {
        o = l[0];
        const d = K(l, o === 0 ? 12 : 20), h = j(r, ["mdia", "hdlr"])[0];
        if (h) {
          const c = rt(h.subarray(8, 12)), f = {
            soun: tt.AUDIO,
            vide: tt.VIDEO
          }[c], g = j(r, ["mdia", "minf", "stbl", "stsd"])[0], p = br(g);
          f ? (t[u] = {
            timescale: d,
            type: f,
            stsd: p
          }, t[f] = ct({
            timescale: d,
            id: u
          }, p)) : t[u] = {
            timescale: d,
            type: c,
            stsd: p
          };
        }
      }
    }
  }
  return j(n, ["moov", "mvex", "trex"]).forEach((s) => {
    const r = K(s, 4), a = t[r];
    a && (a.default = {
      duration: K(s, 12),
      flags: K(s, 20)
    });
  }), t;
}
function br(n) {
  const t = n.subarray(8), e = t.subarray(86), i = rt(t.subarray(4, 8));
  let s = i, r;
  const a = i === "enca" || i === "encv";
  if (a) {
    const l = j(t, [i])[0].subarray(i === "enca" ? 28 : 78);
    j(l, ["sinf"]).forEach((h) => {
      const c = j(h, ["schm"])[0];
      if (c) {
        const f = rt(c.subarray(4, 8));
        if (f === "cbcs" || f === "cenc") {
          const g = j(h, ["frma"])[0];
          g && (s = rt(g));
        }
      }
    });
  }
  const o = s;
  switch (s) {
    case "avc1":
    case "avc2":
    case "avc3":
    case "avc4": {
      const u = j(e, ["avcC"])[0];
      u && u.length > 3 && (s += "." + te(u[1]) + te(u[2]) + te(u[3]), r = Jt(o === "avc1" ? "dva1" : "dvav", e));
      break;
    }
    case "mp4a": {
      const u = j(t, [i])[0], l = j(u.subarray(28), ["esds"])[0];
      if (l && l.length > 7) {
        let d = 4;
        if (l[d++] !== 3)
          break;
        d = Ae(l, d), d += 2;
        const h = l[d++];
        if (h & 128 && (d += 2), h & 64 && (d += l[d++]), l[d++] !== 4)
          break;
        d = Ae(l, d);
        const c = l[d++];
        if (c === 64)
          s += "." + te(c);
        else
          break;
        if (d += 12, l[d++] !== 5)
          break;
        d = Ae(l, d);
        const f = l[d++];
        let g = (f & 248) >> 3;
        g === 31 && (g += 1 + ((f & 7) << 3) + ((l[d] & 224) >> 5)), s += "." + g;
      }
      break;
    }
    case "hvc1":
    case "hev1": {
      const u = j(e, ["hvcC"])[0];
      if (u && u.length > 12) {
        const l = u[1], d = ["", "A", "B", "C"][l >> 6], h = l & 31, c = K(u, 2), f = (l & 32) >> 5 ? "H" : "L", g = u[12], p = u.subarray(6, 12);
        s += "." + d + h, s += "." + Ir(c).toString(16).toUpperCase(), s += "." + f + g;
        let m = "";
        for (let y = p.length; y--; ) {
          const T = p[y];
          (T || m) && (m = "." + T.toString(16).toUpperCase() + m);
        }
        s += m;
      }
      r = Jt(o == "hev1" ? "dvhe" : "dvh1", e);
      break;
    }
    case "dvh1":
    case "dvhe":
    case "dvav":
    case "dva1":
    case "dav1": {
      s = Jt(s, e) || s;
      break;
    }
    case "vp09": {
      const u = j(e, ["vpcC"])[0];
      if (u && u.length > 6) {
        const l = u[4], d = u[5], h = u[6] >> 4 & 15;
        s += "." + vt(l) + "." + vt(d) + "." + vt(h);
      }
      break;
    }
    case "av01": {
      const u = j(e, ["av1C"])[0];
      if (u && u.length > 2) {
        const l = u[1] >>> 5, d = u[1] & 31, h = u[2] >>> 7 ? "H" : "M", c = (u[2] & 64) >> 6, f = (u[2] & 32) >> 5, g = l === 2 && c ? f ? 12 : 10 : c ? 10 : 8, p = (u[2] & 16) >> 4, m = (u[2] & 8) >> 3, y = (u[2] & 4) >> 2, T = u[2] & 3;
        s += "." + l + "." + vt(d) + h + "." + vt(g) + "." + p + "." + m + y + T + "." + vt(1) + "." + vt(1) + "." + vt(1) + "." + 0, r = Jt("dav1", e);
      }
      break;
    }
  }
  return {
    codec: s,
    encrypted: a,
    supplemental: r
  };
}
function Jt(n, t) {
  const e = j(t, ["dvvC"]), i = e.length ? e[0] : j(t, ["dvcC"])[0];
  if (i) {
    const s = i[2] >> 1 & 127, r = i[2] << 5 & 32 | i[3] >> 3 & 31;
    return n + "." + vt(s) + "." + vt(r);
  }
}
function Ir(n) {
  let t = 0;
  for (let e = 0; e < 32; e++)
    t |= (n >> e & 1) << 31 - e;
  return t >>> 0;
}
function Ae(n, t) {
  const e = t + 5;
  for (; n[t++] & 128 && t < e; )
    ;
  return t;
}
function te(n) {
  return ("0" + n.toString(16).toUpperCase()).slice(-2);
}
function vt(n) {
  return (n < 10 ? "0" : "") + n;
}
function Dr(n, t) {
  if (!n || !t)
    return;
  const e = t.keyId;
  e && t.isCommonEncryption && ps(n, (i, s) => {
    const r = i.subarray(8, 24);
    r.some((a) => a !== 0) || (J.log(`[eme] Patching keyId in 'enc${s ? "a" : "v"}>sinf>>tenc' box: ${qt(r)} -> ${qt(e)}`), i.set(e, 8));
  });
}
function Cr(n) {
  const t = [];
  return ps(n, (e) => t.push(e.subarray(8, 24))), t;
}
function ps(n, t) {
  j(n, ["moov", "trak"]).forEach((i) => {
    const s = j(i, ["mdia", "minf", "stbl", "stsd"])[0];
    if (!s) return;
    const r = s.subarray(8);
    let a = j(r, ["enca"]);
    const o = a.length > 0;
    o || (a = j(r, ["encv"])), a.forEach((u) => {
      const l = o ? u.subarray(28) : u.subarray(78);
      j(l, ["sinf"]).forEach((h) => {
        const c = _r(h);
        c && t(c, o);
      });
    });
  });
}
function _r(n) {
  const t = j(n, ["schm"])[0];
  if (t) {
    const e = rt(t.subarray(4, 8));
    if (e === "cbcs" || e === "cenc") {
      const i = j(n, ["schi", "tenc"])[0];
      if (i)
        return i;
    }
  }
}
function Pr(n, t, e) {
  const i = {}, s = j(n, ["moof", "traf"]);
  for (let r = 0; r < s.length; r++) {
    const a = s[r], o = j(a, ["tfhd"])[0], u = K(o, 4), l = t[u];
    if (!l)
      continue;
    i[u] || (i[u] = {
      start: NaN,
      duration: 0,
      sampleCount: 0,
      timescale: l.timescale,
      type: l.type
    });
    const d = i[u], h = j(a, ["tfdt"])[0];
    if (h) {
      const v = h[0];
      let x = K(h, 4);
      v === 1 && (x === ui ? e.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time") : (x *= ui + 1, x += K(h, 8))), B(x) && (!B(d.start) || x < d.start) && (d.start = x);
    }
    const c = l.default, f = K(o, 0) | c?.flags;
    let g = c?.duration || 0;
    f & 8 && (f & 2 ? g = K(o, 12) : g = K(o, 8));
    const p = j(a, ["trun"]);
    let m = d.start || 0, y = 0, T = g;
    for (let v = 0; v < p.length; v++) {
      const x = p[v], A = K(x, 4), C = d.sampleCount;
      d.sampleCount += A;
      const S = x[3] & 1, R = x[3] & 4, b = x[2] & 1, I = x[2] & 2, _ = x[2] & 4, F = x[2] & 8;
      let $ = 8, V = A;
      for (S && ($ += 4), R && A && (!(x[$ + 1] & 1) && d.keyFrameIndex === void 0 && (d.keyFrameIndex = C), $ += 4, b ? (T = K(x, $), $ += 4) : T = g, I && ($ += 4), F && ($ += 4), m += T, y += T, V--); V--; )
        b ? (T = K(x, $), $ += 4) : T = g, I && ($ += 4), _ && (x[$ + 1] & 1 || d.keyFrameIndex === void 0 && (d.keyFrameIndex = d.sampleCount - (V + 1), d.keyFrameStart = m), $ += 4), F && ($ += 4), m += T, y += T;
      !y && g && (y += g * A);
    }
    d.duration += y;
  }
  if (!Object.keys(i).some((r) => i[r].duration)) {
    let r = 1 / 0, a = 0;
    const o = j(n, ["sidx"]);
    for (let u = 0; u < o.length; u++) {
      const l = Rr(o[u]);
      if (l != null && l.references) {
        r = Math.min(r, l.earliestPresentationTime / l.timescale);
        const d = l.references.reduce((h, c) => h + c.info.duration || 0, 0);
        a = Math.max(a, d + l.earliestPresentationTime / l.timescale);
      }
    }
    a && B(a) && Object.keys(i).forEach((u) => {
      i[u].duration || (i[u].duration = a * i[u].timescale - i[u].start);
    });
  }
  return i;
}
function kr(n) {
  const t = {
    valid: null,
    remainder: null
  }, e = j(n, ["moof"]);
  if (e.length < 2)
    return t.remainder = n, t;
  const i = e[e.length - 1];
  return t.valid = n.slice(0, i.byteOffset - 8), t.remainder = n.slice(i.byteOffset - 8), t;
}
function mt(n, t) {
  const e = new Uint8Array(n.length + t.length);
  return e.set(n), e.set(t, n.length), e;
}
function hi(n, t) {
  const e = [], i = t.samples, s = t.timescale, r = t.id;
  let a = !1;
  return j(i, ["moof"]).map((u) => {
    const l = u.byteOffset - 8;
    j(u, ["traf"]).map((h) => {
      const c = j(h, ["tfdt"]).map((f) => {
        const g = f[0];
        let p = K(f, 4);
        return g === 1 && (p *= Math.pow(2, 32), p += K(f, 8)), p / s;
      })[0];
      return c !== void 0 && (n = c), j(h, ["tfhd"]).map((f) => {
        const g = K(f, 4), p = K(f, 0) & 16777215, m = (p & 1) !== 0, y = (p & 2) !== 0, T = (p & 8) !== 0;
        let v = 0;
        const x = (p & 16) !== 0;
        let A = 0;
        const C = (p & 32) !== 0;
        let S = 8;
        g === r && (m && (S += 8), y && (S += 4), T && (v = K(f, S), S += 4), x && (A = K(f, S), S += 4), C && (S += 4), t.type === "video" && (a = ze(t.codec)), j(h, ["trun"]).map((R) => {
          const b = R[0], I = K(R, 0) & 16777215, _ = (I & 1) !== 0;
          let F = 0;
          const $ = (I & 4) !== 0, V = (I & 256) !== 0;
          let N = 0;
          const P = (I & 512) !== 0;
          let G = 0;
          const M = (I & 1024) !== 0, U = (I & 2048) !== 0;
          let H = 0;
          const O = K(R, 4);
          let w = 8;
          _ && (F = K(R, w), w += 4), $ && (w += 4);
          let z = F + l;
          for (let Z = 0; Z < O; Z++) {
            if (V ? (N = K(R, w), w += 4) : N = v, P ? (G = K(R, w), w += 4) : G = A, M && (w += 4), U && (b === 0 ? H = K(R, w) : H = gs(R, w), w += 4), t.type === tt.VIDEO) {
              let Q = 0;
              for (; Q < G; ) {
                const et = K(i, z);
                if (z += 4, Or(a, i[z])) {
                  const pt = i.subarray(z, z + et);
                  Es(pt, a ? 2 : 1, n + H / s, e);
                }
                z += et, Q += et + 4;
              }
            }
            n += N / s;
          }
        }));
      });
    });
  }), e;
}
function ze(n) {
  if (!n)
    return !1;
  const t = n.substring(0, 4);
  return t === "hvc1" || t === "hev1" || // Dolby Vision
  t === "dvh1" || t === "dvhe";
}
function Or(n, t) {
  if (n) {
    const e = t >> 1 & 63;
    return e === 39 || e === 40;
  } else
    return (t & 31) === 6;
}
function Es(n, t, e, i) {
  const s = vs(n);
  let r = 0;
  r += t;
  let a = 0, o = 0, u = 0;
  for (; r < s.length; ) {
    a = 0;
    do {
      if (r >= s.length)
        break;
      u = s[r++], a += u;
    } while (u === 255);
    o = 0;
    do {
      if (r >= s.length)
        break;
      u = s[r++], o += u;
    } while (u === 255);
    const l = s.length - r;
    let d = r;
    if (o < l)
      r += o;
    else if (o > l) {
      J.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);
      break;
    }
    if (a === 4) {
      if (s[d++] === 181) {
        const c = fs(s, d);
        if (d += 2, c === 49) {
          const f = K(s, d);
          if (d += 4, f === 1195456820) {
            const g = s[d++];
            if (g === 3) {
              const p = s[d++], m = 31 & p, y = 64 & p, T = y ? 2 + m * 3 : 0, v = new Uint8Array(T);
              if (y) {
                v[0] = p;
                for (let x = 1; x < T; x++)
                  v[x] = s[d++];
              }
              i.push({
                type: g,
                payloadType: a,
                pts: e,
                bytes: v
              });
            }
          }
        }
      }
    } else if (a === 5 && o > 16) {
      const h = [];
      for (let g = 0; g < 16; g++) {
        const p = s[d++].toString(16);
        h.push(p.length == 1 ? "0" + p : p), (g === 3 || g === 5 || g === 7 || g === 9) && h.push("-");
      }
      const c = o - 16, f = new Uint8Array(c);
      for (let g = 0; g < c; g++)
        f[g] = s[d++];
      i.push({
        payloadType: a,
        pts: e,
        uuid: h.join(""),
        userData: gt(f),
        userDataBytes: f
      });
    }
  }
}
function vs(n) {
  const t = n.byteLength, e = [];
  let i = 1;
  for (; i < t - 2; )
    n[i] === 0 && n[i + 1] === 0 && n[i + 2] === 3 ? (e.push(i + 2), i += 2) : i++;
  if (e.length === 0)
    return n;
  const s = t - e.length, r = new Uint8Array(s);
  let a = 0;
  for (i = 0; i < s; a++, i++)
    a === e[0] && (a++, e.shift()), r[i] = n[a];
  return r;
}
function wr(n) {
  const t = n[0];
  let e = "", i = "", s = 0, r = 0, a = 0, o = 0, u = 0, l = 0;
  if (t === 0) {
    for (; rt(n.subarray(l, l + 1)) !== "\0"; )
      e += rt(n.subarray(l, l + 1)), l += 1;
    for (e += rt(n.subarray(l, l + 1)), l += 1; rt(n.subarray(l, l + 1)) !== "\0"; )
      i += rt(n.subarray(l, l + 1)), l += 1;
    i += rt(n.subarray(l, l + 1)), l += 1, s = K(n, 12), r = K(n, 16), o = K(n, 20), u = K(n, 24), l = 28;
  } else if (t === 1) {
    l += 4, s = K(n, l), l += 4;
    const h = K(n, l);
    l += 4;
    const c = K(n, l);
    for (l += 4, a = 2 ** 32 * h + c, or(a) || (a = Number.MAX_SAFE_INTEGER, J.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")), o = K(n, l), l += 4, u = K(n, l), l += 4; rt(n.subarray(l, l + 1)) !== "\0"; )
      e += rt(n.subarray(l, l + 1)), l += 1;
    for (e += rt(n.subarray(l, l + 1)), l += 1; rt(n.subarray(l, l + 1)) !== "\0"; )
      i += rt(n.subarray(l, l + 1)), l += 1;
    i += rt(n.subarray(l, l + 1)), l += 1;
  }
  const d = n.subarray(l, n.byteLength);
  return {
    schemeIdUri: e,
    value: i,
    timeScale: s,
    presentationTime: a,
    presentationTimeDelta: r,
    eventDuration: o,
    id: u,
    payload: d
  };
}
const ys = () => /\(Windows.+Firefox\//i.test(navigator.userAgent), Gt = {
  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 Xe(n, t) {
  const e = Gt[t];
  return !!e && !!e[n.slice(0, 4)];
}
function zt(n, t, e = !0) {
  return !n.split(",").some((i) => !Qe(i, t, e));
}
function Qe(n, t, e = !0) {
  var i;
  const s = _t(e);
  return (i = s?.isTypeSupported(Xt(n, t))) != null ? i : !1;
}
function Xt(n, t) {
  return `${t}/mp4;codecs=${n}`;
}
function ci(n) {
  if (n) {
    const t = n.substring(0, 4);
    return Gt.video[t];
  }
  return 2;
}
function he(n) {
  const t = ys();
  return n.split(",").reduce((e, i) => {
    const r = t && ze(i) ? 9 : Gt.video[i];
    return r ? (r * 2 + e) / (e ? 3 : 2) : (Gt.audio[i] + e) / (e ? 2 : 1);
  }, 0);
}
const Re = {};
function Fr(n, t = !0) {
  if (Re[n])
    return Re[n];
  const e = {
    // 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"]
  }[n];
  for (let s = 0; s < e.length; s++) {
    var i;
    if (Qe(e[s], "audio", t))
      return Re[n] = e[s], e[s];
    if (e[s] === "mp3" && (i = _t(t)) != null && i.isTypeSupported("audio/mpeg"))
      return "";
  }
  return n;
}
const Mr = /flac|opus|mp4a\.40\.34/i;
function ce(n, t = !0) {
  return n.replace(Mr, (e) => Fr(e.toLowerCase(), t));
}
function Nr(n, t) {
  const e = [];
  if (n) {
    const i = n.split(",");
    for (let s = 0; s < i.length; s++)
      Xe(i[s], "video") || e.push(i[s]);
  }
  return t && e.push(t), e.join(",");
}
function le(n, t) {
  if (n && (n.length > 4 || ["ac-3", "ec-3", "alac", "fLaC", "Opus"].indexOf(n) !== -1) && (fi(n, "audio") || fi(n, "video")))
    return n;
  if (t) {
    const e = t.split(",");
    if (e.length > 1) {
      if (n) {
        for (let i = e.length; i--; )
          if (e[i].substring(0, 4) === n.substring(0, 4))
            return e[i];
      }
      return e[0];
    }
  }
  return t || n;
}
function fi(n, t) {
  return Xe(n, t) && Qe(n, t);
}
function Br(n) {
  const t = n.split(",");
  for (let e = 0; e < t.length; e++) {
    const i = t[e].split(".");
    i.length > 2 && i[0] === "avc1" && (t[e] = `avc1.${parseInt(i[1]).toString(16)}${("000" + parseInt(i[2]).toString(16)).slice(-4)}`);
  }
  return t.join(",");
}
function $r(n) {
  if (n.startsWith("av01.")) {
    const t = n.split("."), e = ["0", "111", "01", "01", "01", "0"];
    for (let i = t.length; i > 4 && i < 10; i++)
      t[i] = e[i - 4];
    return t.join(".");
  }
  return n;
}
function gi(n) {
  const t = _t(n) || {
    isTypeSupported: () => !1
  };
  return {
    mpeg: t.isTypeSupported("audio/mpeg"),
    mp3: t.isTypeSupported('audio/mp4; codecs="mp3"'),
    ac3: !1
  };
}
function Ue(n) {
  return n.replace(/^.+codecs=["']?([^"']+).*$/, "$1");
}
const Ge = ["NONE", "TYPE-0", "TYPE-1", null];
function Ur(n) {
  return Ge.indexOf(n) > -1;
}
const fe = ["SDR", "PQ", "HLG"];
function Gr(n) {
  return !!n && fe.indexOf(n) > -1;
}
var ue = {
  No: "",
  Yes: "YES",
  v2: "v2"
};
function mi(n) {
  const {
    canSkipUntil: t,
    canSkipDateRanges: e,
    age: i
  } = n, s = i < t / 2;
  return t && s ? e ? ue.v2 : ue.Yes : ue.No;
}
class pi {
  constructor(t, e, i) {
    this.msn = void 0, this.part = void 0, this.skip = void 0, this.msn = t, this.part = e, this.skip = i;
  }
  addDirectives(t) {
    const e = new self.URL(t);
    return this.msn !== void 0 && e.searchParams.set("_HLS_msn", this.msn.toString()), this.part !== void 0 && e.searchParams.set("_HLS_part", this.part.toString()), this.skip && e.searchParams.set("_HLS_skip", this.skip), e.href;
  }
}
class Ts {
  constructor(t) {
    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 = [t.url], this._attrs = [t.attrs], this.bitrate = t.bitrate, t.details && (this.details = t.details), this.id = t.id || 0, this.name = t.name, this.width = t.width || 0, this.height = t.height || 0, this.frameRate = t.attrs.optionalFloat("FRAME-RATE", 0), this._avgBitrate = t.attrs.decimalInteger("AVERAGE-BANDWIDTH"), this.audioCodec = t.audioCodec, this.videoCodec = t.videoCodec, this.codecSet = [t.videoCodec, t.audioCodec].filter((i) => !!i).map((i) => i.substring(0, 4)).join(","), "supplemental" in t) {
      var e;
      this.supplemental = t.supplemental;
      const i = (e = t.supplemental) == null ? void 0 : e.videoCodec;
      i && i !== t.videoCodec && (this.codecSet += `,${i.substring(0, 4)}`);
    }
    this.addGroupId("audio", t.attrs.AUDIO), this.addGroupId("text", t.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(t) {
    return Ei(this._audioGroups, t);
  }
  hasSubtitleGroup(t) {
    return Ei(this._subtitleGroups, t);
  }
  get audioGroups() {
    return this._audioGroups;
  }
  get subtitleGroups() {
    return this._subtitleGroups;
  }
  addGroupId(t, e) {
    if (e) {
      if (t === "audio") {
        let i = this._audioGroups;
        i || (i = this._audioGroups = []), i.indexOf(e) === -1 && i.push(e);
      } else if (t === "text") {
        let i = this._subtitleGroups;
        i || (i = this._subtitleGroups = []), i.indexOf(e) === -1 && i.push(e);
      }
    }
  }
  // Deprecated methods (retained for backwards compatibility)
  get urlId() {
    return 0;
  }
  set urlId(t) {
  }
  get audioGroupIds() {
    return this.audioGroups ? [this.audioGroupId] : void 0;
  }
  get textGroupIds() {
    return this.subtitleGroups ? [this.textGroupId] : void 0;
  }
  get audioGroupId() {
    var t;
    return (t = this.audioGroups) == null ? void 0 : t[0];
  }
  get textGroupId() {
    var t;
    return (t = this.subtitleGroups) == null ? void 0 : t[0];
  }
  addFallback() {
  }
}
function Ei(n, t) {
  return !t || !n ? !1 : n.indexOf(t) !== -1;
}
function Vr() {
  if (typeof matchMedia == "function") {
    const n = matchMedia("(dynamic-range: high)"), t = matchMedia("bad query");
    if (n.media !== t.media)
      return n.matches === !0;
  }
  return !1;
}
function Hr(n, t) {
  let e = !1, i = [];
  if (n && (e = n !== "SDR", i = [n]), t) {
    i = t.allowedVideoRanges || fe.slice(0);
    const s = i.join("") !== "SDR" && !t.videoCodec;
    e = t.preferHDR !== void 0 ? t.preferHDR : s && Vr(), e || (i = ["SDR"]);
  }
  return {
    preferHDR: e,
    allowedVideoRanges: i
  };
}
const Kr = (n) => {
  const t = /* @__PURE__ */ new WeakSet();
  return (e, i) => {
    if (n && (i = n(e, i)), typeof i == "object" && i !== null) {
      if (t.has(i))
        return;
      t.add(i);
    }
    return i;
  };
}, ot = (n, t) => JSON.stringify(n, Kr(t));
function Wr(n, t, e, i, s) {
  const r = Object.keys(n), a = i?.channels, o = i?.audioCodec, u = s?.videoCodec, l = a && parseInt(a) === 2;
  let d = !1, h = !1, c = 1 / 0, f = 1 / 0, g = 1 / 0, p = 1 / 0, m = 0, y = [];
  const {
    preferHDR: T,
    allowedVideoRanges: v
  } = Hr(t, s);
  for (let R = r.length; R--; ) {
    const b = n[r[R]];
    d || (d = b.channels[2] > 0), c = Math.min(c, b.minHeight), f = Math.min(f, b.minFramerate), g = Math.min(g, b.minBitrate), v.filter((_) => b.videoRanges[_] > 0).length > 0 && (h = !0);
  }
  c = B(c) ? c : 0, f = B(f) ? f : 0;
  const x = Math.max(1080, c), A = Math.max(30, f);
  g = B(g) ? g : e, e = Math.max(g, e), h || (t = void 0);
  const C = r.length > 1;
  return {
    codecSet: r.reduce((R, b) => {
      const I = n[b];
      if (b === R)
        return R;
      if (y = h ? v.filter((_) => I.videoRanges[_] > 0) : [], C) {
        if (I.minBitrate > e)
          return Et(b, `min bitrate of ${I.minBitrate} > current estimate of ${e}`), R;
        if (!I.hasDefaultAudio)
          return Et(b, "no renditions with default or auto-select sound found"), R;
        if (o && b.indexOf(o.substring(0, 4)) % 5 !== 0)
          return Et(b, `audio codec preference "${o}" not found`), R;
        if (a && !l) {
          if (!I.channels[a])
            return Et(b, `no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`), R;
        } else if ((!o || l) && d && I.channels[2] === 0)
          return Et(b, "no renditions with stereo sound found"), R;
        if (I.minHeight > x)
          return Et(b, `min resolution of ${I.minHeight} > maximum of ${x}`), R;
        if (I.minFramerate > A)
          return Et(b, `min framerate of ${I.minFramerate} > maximum of ${A}`), R;
        if (!y.some((_) => I.videoRanges[_] > 0))
          return Et(b, `no variants with VIDEO-RANGE of ${ot(y)} found`), R;
        if (u && b.indexOf(u.substring(0, 4)) % 5 !== 0)
          return Et(b, `video codec preference "${u}" not found`), R;
        if (I.maxScore < m)
          return Et(b, `max score of ${I.maxScore} < selected max of ${m}`), R;
      }
      return R && (he(b) >= he(R) || I.fragmentError > n[R].fragmentError) ? R : (p = I.minIndex, m = I.maxScore, b);
    }, void 0),
    videoRanges: y,
    preferHDR: T,
    minFramerate: f,
    minBitrate: g,
    minIndex: p
  };
}
function Et(n, t) {
  J.log(`[abr] start candidates with "${n}" ignored because ${t}`);
}
function xs(n) {
  return n.reduce((t, e) => {
    let i = t.groups[e.groupId];
    i || (i = t.groups[e.groupId] = {
      tracks: [],
      channels: {
        2: 0
      },
      hasDefault: !1,
      hasAutoSelect: !1
    }), i.tracks.push(e);
    const s = e.channels || "2";
    return i.channels[s] = (i.channels[s] || 0) + 1, i.hasDefault = i.hasDefault || e.default, i.hasAutoSelect = i.hasAutoSelect || e.autoselect, i.hasDefault && (t.hasDefaultAudio = !0), i.hasAutoSelect && (t.hasAutoSelectAudio = !0), t;
  }, {
    hasDefaultAudio: !1,
    hasAutoSelectAudio: !1,
    groups: {}
  });
}
function Yr(n, t, e, i) {
  return n.slice(e, i + 1).reduce((s, r, a) => {
    if (!r.codecSet)
      return s;
    const o = r.audioGroups;
    let u = s[r.codecSet];
    u || (s[r.codecSet] = u = {
      minBitrate: 1 / 0,
      minHeight: 1 / 0,
      minFramerate: 1 / 0,
      minIndex: a,
      maxScore: 0,
      videoRanges: {
        SDR: 0
      },
      channels: {
        2: 0
      },
      hasDefaultAudio: !o,
      fragmentError: 0
    }), u.minBitrate = Math.min(u.minBitrate, r.bitrate);
    const l = Math.min(r.height, r.width);
    return u.minHeight = Math.min(u.minHeight, l), u.minFramerate = Math.min(u.minFramerate, r.frameRate), u.minIndex = Math.min(u.minIndex, a), u.maxScore = Math.max(u.maxScore, r.score), u.fragmentError += r.fragmentError, u.videoRanges[r.videoRange] = (u.videoRanges[r.videoRange] || 0) + 1, s;
  }, {});
}
function vi(n, t) {
  var e;
  return !!n && n !== ((e = t.loadLevelObj) == null ? void 0 : e.uri);
}
class jr extends Rt {
  constructor(t) {
    super("abr", t.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 = (e) => {
      var i;
      const {
        fragCurrent: s,
        partCurrent: r,
        hls: a
      } = this, {
        autoLevelEnabled: o,
        media: u
      } = a;
      if (!s || !u)
        return;
      const l = performance.now(), d = r ? r.stats : s.stats, h = r ? r.duration : s.duration, c = l - d.loading.start, f = a.minAutoLevel, g = s.level, p = this._nextAutoLevel;
      if (d.aborted || d.loaded && d.loaded === d.total || g <= f) {
        this.clearTimer(), this._nextAutoLevel = -1;
        return;
      }
      if (!o)
        return;
      const m = p > -1 && p !== g, y = !!e || m;
      if (!y && (u.paused || !u.playbackRate || !u.readyState))
        return;
      const T = a.mainForwardBufferInfo;
      if (!y && T === null)
        return;
      const v = this.bwEstimator.getEstimateTTFB(), x = Math.abs(u.playbackRate);
      if (c <= Math.max(v, 1e3 * (h / (x * 2))))
        return;
      const A = T ? T.len / x : 0, C = d.loading.first ? d.loading.first - d.loading.start : -1, S = d.loaded && C > -1, R = this.getBwEstimate(), b = a.levels, I = b[g], _ = Math.max(d.loaded, Math.round(h * (s.bitrate || I.averageBitrate) / 8));
      let F = S ? c - C : c;
      F < 1 && S && (F = Math.min(c, d.loaded * 8 / R));
      const $ = S ? d.loaded * 1e3 / F : 0, V = v / 1e3, N = $ ? (_ - d.loaded) / $ : _ * 8 / R + V;
      if (N <= A)
        return;
      const P = $ ? $ * 8 : R, G = ((i = e?.details || this.hls.latestLevelDetails) == null ? void 0 : i.live) === !0, M = this.hls.config.abrBandWidthUpFactor;
      let U = Number.POSITIVE_INFINITY, H;
      for (H = g - 1; H > f; H--) {
        const Z = b[H].maxBitrate, Q = !b[H].details || G;
        if (U = this.getTimeToLoadFrag(V, P, h * Z, Q), U < Math.min(A, h + V))
          break;
      }
      if (U >= N || U > h * 10)
        return;
      S ? this.bwEstimator.sample(c - Math.min(v, C), d.loaded) : this.bwEstimator.sampleTTFB(c);
      const O = b[H].maxBitrate;
      this.getBwEstimate() * M > O && this.resetEstimator(O);
      const w = this.findBestLevel(O, f, H, 0, A, 1, 1);
      w > -1 && (H = w), this.warn(`Fragment ${s.sn}${r ? " part " + r.index : ""} of level ${g} is loading too slowly;
      Fragment duration: ${s.duration.toFixed(3)}
      Time to underbuffer: ${A.toFixed(3)} s
      Estimated load time for current fragment: ${N.toFixed(3)} s
      Estimated load time for down switch fragment: ${U.toFixed(3)} s
      TTFB estimate: ${C | 0} ms
      Current BW estimate: ${B(R) ? R | 0 : "Unknown"} bps
      New BW estimate: ${this.getBwEstimate() | 0} bps
      Switching to level ${H} @ ${O | 0} bps`), a.nextLoadLevel = a.nextAutoLevel = H, this.clearTimer();
      const z = () => {
        if (this.clearTimer(), this.fragCurrent === s && this.hls.loadLevel === H && H > 0) {
          const Z = this.getStarvationDelay();
          if (this.warn(`Aborting inflight request ${H > 0 ? "and switching down" : ""}
      Fragment duration: ${s.duration.toFixed(3)} s
      Time to underbuffer: ${Z.toFixed(3)} s`), s.abortRequests(), this.fragCurrent = this.partCurrent = null, H > f) {
            let Q = this.findBestLevel(this.hls.levels[f].bitrate, f, H, 0, Z, 1, 1);
            Q === -1 && (Q = f), this.hls.nextLoadLevel = this.hls.nextAutoLevel = Q, this.resetEstimator(this.hls.levels[Q].bitrate);
          }
        }
      };
      m || N > U * 2 ? z() : this.timer = self.setInterval(z, U * 1e3), a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED, {
        frag: s,
        part: r,
        stats: d
      });
    }, this.hls = t, this.bwEstimator = this.initEstimator(), this.registerListeners();
  }
  resetEstimator(t) {
    t && (this.log(`setting initial bwe to ${t}`), this.hls.config.abrEwmaDefaultEstimate = t), this.firstSelection = -1, this.bwEstimator = this.initEstimator();
  }
  initEstimator() {
    const t = this.hls.config;
    return new ur(t.abrEwmaSlowVoD, t.abrEwmaFastVoD, t.abrEwmaDefaultEstimate);
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.FRAG_LOADING, this.onFragLoading, this), t.on(E.FRAG_LOADED, this.onFragLoaded, this), t.on(E.FRAG_BUFFERED, this.onFragBuffered, this), t.on(E.LEVEL_SWITCHING, this.onLevelSwitching, this), t.on(E.LEVEL_LOADED, this.onLevelLoaded, this), t.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.on(E.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this), t.on(E.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t && (t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.FRAG_LOADING, this.onFragLoading, this), t.off(E.FRAG_LOADED, this.onFragLoaded, this), t.off(E.FRAG_BUFFERED, this.onFragBuffered, this), t.off(E.LEVEL_SWITCHING, this.onLevelSwitching, this), t.off(E.LEVEL_LOADED, this.onLevelLoaded, this), t.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.off(E.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this), t.off(E.ERROR, this.onError, this));
  }
  destroy() {
    this.unregisterListeners(), this.clearTimer(), this.hls = this._abandonRulesCheck = this.supportedCache = null, this.fragCurrent = this.partCurrent = null;
  }
  onManifestLoading(t, e) {
    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(t, e) {
    const i = e.frag;
    if (!this.ignoreFragment(i)) {
      if (!i.bitrateTest) {
        var s;
        this.fragCurrent = i, this.partCurrent = (s = e.part) != null ? s : null;
      }
      this.clearTimer(), this.timer = self.setInterval(this._abandonRulesCheck, 100);
    }
  }
  onLevelSwitching(t, e) {
    this.clearTimer();
  }
  onError(t, e) {
    if (!e.fatal)
      switch (e.details) {
        case D.BUFFER_ADD_CODEC_ERROR:
        case D.BUFFER_APPEND_ERROR:
          this.lastLoadedFragLevel = -1, this.firstSelection = -1;
          break;
        case D.FRAG_LOAD_TIMEOUT: {
          const i = e.frag, {
            fragCurrent: s,
            partCurrent: r
          } = this;
          if (i && s && i.sn === s.sn && i.level === s.level) {
            const a = performance.now(), o = r ? r.stats : i.stats, u = 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(u - Math.min(h, l), o.loaded);
            } else
              this.bwEstimator.sampleTTFB(u);
          }
          break;
        }
      }
  }
  getTimeToLoadFrag(t, e, i, s) {
    const r = t + i / e, a = s ? t + this.lastLevelLoadSec : 0;
    return r + a;
  }
  onLevelLoaded(t, e) {
    const i = this.hls.config, {
      loading: s
    } = e.stats, r = s.end - s.first;
    B(r) && (this.lastLevelLoadSec = r / 1e3), e.details.live ? this.bwEstimator.update(i.abrEwmaSlowLive, i.abrEwmaFastLive) : this.bwEstimator.update(i.abrEwmaSlowVoD, i.abrEwmaFastVoD), this.timer > -1 && this._abandonRulesCheck(e.levelInfo);
  }
  onFragLoaded(t, {
    frag: e,
    part: i
  }) {
    const s = i ? i.stats : e.stats;
    if (e.type === W.MAIN && this.bwEstimator.sampleTTFB(s.loading.first - s.loading.start), !this.ignoreFragment(e)) {
      if (this.clearTimer(), e.level === this._nextAutoLevel && (this._nextAutoLevel = -1), this.firstSelection = -1, this.hls.config.abrMaxWithRealBitrate) {
        const r = i ? i.duration : e.duration, a = this.hls.levels[e.level], o = (a.loaded ? a.loaded.bytes : 0) + s.loaded, u = (a.loaded ? a.loaded.duration : 0) + r;
        a.loaded = {
          bytes: o,
          duration: u
        }, a.realBitrate = Math.round(8 * o / u);
      }
      if (e.bitrateTest) {
        const r = {
          stats: s,
          frag: e,
          part: i,
          id: e.type
        };
        this.onFragBuffered(E.FRAG_BUFFERED, r), e.bitrateTest = !1;
      } else
        this.lastLoadedFragLevel = e.level;
    }
  }
  onFragBuffered(t, e) {
    const {
      frag: i,
      part: s
    } = e, r = s != null && s.stats.loaded ? s.stats : i.stats;
    if (r.aborted || this.ignoreFragment(i))
      return;
    const a = r.parsing.end - r.loading.start - Math.min(r.loading.first - r.loading.start, this.bwEstimator.getEstimateTTFB());
    this.bwEstimator.sample(a, r.loaded), r.bwEstimate = this.getBwEstimate(), i.bitrateTest ? this.bitrateTestDelay = a / 1e3 : this.bitrateTestDelay = 0;
  }
  ignoreFragment(t) {
    return t.type !== W.MAIN || t.sn === "initSegment";
  }
  clearTimer() {
    this.timer > -1 && (self.clearInterval(this.timer), this.timer = -1);
  }
  get firstAutoLevel() {
    const {
      maxAutoLevel: t,
      minAutoLevel: e
    } = this.hls, i = this.getBwEstimate(), s = this.hls.config.maxStarvationDelay, r = this.findBestLevel(i, e, t, 0, s, 1, 1);
    if (r > -1)
      return r;
    const a = this.hls.firstLevel, o = Math.min(Math.max(a, e), t);
    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 t = this.forcedAutoLevel, i = this.bwEstimator.canEstimate(), s = this.lastLoadedFragLevel > -1;
    if (t !== -1 && (!i || !s || this.nextAutoLevelKey === this.getAutoLevelKey()))
      return t;
    const r = i && s ? this.getNextABRAutoLevel() : this.firstAutoLevel;
    if (t !== -1) {
      const a = this.hls.levels;
      if (a.length > Math.max(t, r) && a[t].loadError <= a[r].loadError)
        return t;
    }
    return this._nextAutoLevel = r, this.nextAutoLevelKey = this.getAutoLevelKey(), r;
  }
  getAutoLevelKey() {
    return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  }
  getNextABRAutoLevel() {
    const {
      fragCurrent: t,
      partCurrent: e,
      hls: i
    } = this;
    if (i.levels.length <= 1)
      return i.loadLevel;
    const {
      maxAutoLevel: s,
      config: r,
      minAutoLevel: a
    } = i, o = e ? e.duration : t ? t.duration : 0, u = this.getBwEstimate(), l = this.getStarvationDelay();
    let d = r.abrBandWidthFactor, h = r.abrBandWidthUpFactor;
    if (l) {
      const m = this.findBestLevel(u, a, s, l, 0, d, h);
      if (m >= 0)
        return this.rebufferNotice = -1, m;
    }
    let c = o ? Math.min(o, r.maxStarvationDelay) : r.maxStarvationDelay;
    if (!l) {
      const m = this.bitrateTestDelay;
      m && (c = (o ? Math.min(o, r.maxLoadingDelay) : r.maxLoadingDelay) - m, this.info(`bitrate test took ${Math.round(1e3 * m)}ms, set first fragment max fetchDuration to ${Math.round(1e3 * c)} ms`), d = h = 1);
    }
    const f = this.findBestLevel(u, a, s, l, c, 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 g = i.levels[a], p = i.loadLevelObj;
    return p && g?.bitrate < p.bitrate ? a : i.loadLevel;
  }
  getStarvationDelay() {
    const t = this.hls, e = t.media;
    if (!e)
      return 1 / 0;
    const i = e && e.playbackRate !== 0 ? Math.abs(e.playbackRate) : 1, s = t.mainForwardBufferInfo;
    return (s ? s.len : 0) / i;
  }
  getBwEstimate() {
    return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  }
  findBestLevel(t, e, i, s, r, a, o) {
    var u;
    const l = s + r, d = this.lastLoadedFragLevel, h = d === -1 ? this.hls.firstLevel : d, {
      fragCurrent: c,
      partCurrent: f
    } = this, {
      levels: g,
      allAudioTracks: p,
      loadLevel: m,
      config: y
    } = this.hls;
    if (g.length === 1)
      return 0;
    const T = g[h], v = !!((u = this.hls.latestLevelDetails) != null && u.live), x = m === -1 || d === -1;
    let A, C = "SDR", S = T?.frameRate || 0;
    const {
      audioPreference: R,
      videoPreference: b
    } = y, I = this.audioTracksByGroup || (this.audioTracksByGroup = xs(p));
    let _ = -1;
    if (x) {
      if (this.firstSelection !== -1)
        return this.firstSelection;
      const P = this.codecTiers || (this.codecTiers = Yr(g, I, e, i)), G = Wr(P, C, t, R, b), {
        codecSet: M,
        videoRanges: U,
        minFramerate: H,
        minBitrate: O,
        minIndex: w,
        preferHDR: z
      } = G;
      _ = w, A = M, C = z ? U[U.length - 1] : U[0], S = H, t = Math.max(t, O), this.log(`picked start tier ${ot(G)}`);
    } else
      A = T?.codecSet, C = T?.videoRange;
    const F = f ? f.duration : c ? c.duration : 0, $ = this.bwEstimator.getEstimateTTFB() / 1e3, V = [];
    for (let P = i; P >= e; P--) {
      var N;
      const G = g[P], M = P > h;
      if (!G)
        continue;
      if ((A && G.codecSet !== A || C && G.videoRange !== C || M && S > G.frameRate || !M && S > 0 && S < G.frameRate || (N = G.supportedResult) != null && (N = N.decodingInfoResults) != null && N.some((Q) => Q.smooth === !1)) && (!x || P !== _)) {
        V.push(P);
        continue;
      }
      const U = G.details, H = (f ? U?.partTarget : U?.averagetargetduration) || F;
      let O;
      M ? O = o * t : O = a * t;
      const w = F && s >= F * 2 && r === 0 ? G.averageBitrate : G.maxBitrate, z = this.getTimeToLoadFrag($, O, w * H, U === void 0);
      if (
        // if adjusted bw is greater than level bitrate AND
        O >= w && // no level change, or new level has no error history
        (P === d || G.loadError === 0 && G.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
        (z <= $ || !B(z) || v && !this.bitrateTestDelay || z < l)
      ) {
        const Q = this.forcedAutoLevel;
        return P !== m && (Q === -1 || Q !== m) && (V.length && this.trace(`Skipped level(s) ${V.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[V[0]].codecs}" ${g[V[0]].videoRange}; not compatible with "${A}" ${C}`), this.info(`switch candidate:${h}->${P} adjustedbw(${Math.round(O)})-bitrate=${Math.round(O - w)} ttfb:${$.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${z.toFixed(1)} firstSelection:${x} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${m}`)), x && (this.firstSelection = P), P;
      }
    }
    return -1;
  }
  set nextAutoLevel(t) {
    const e = this.deriveNextAutoLevel(t);
    this._nextAutoLevel !== e && (this.nextAutoLevelKey = "", this._nextAutoLevel = e);
  }
  deriveNextAutoLevel(t) {
    const {
      maxAutoLevel: e,
      minAutoLevel: i
    } = this.hls;
    return Math.min(Math.max(t, i), e);
  }
}
const Ss = {
  /**
   * 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(n, t) {
    let e = 0, i = n.length - 1, s = null, r = null;
    for (; e <= i; ) {
      s = (e + i) / 2 | 0, r = n[s];
      const a = t(r);
      if (a > 0)
        e = s + 1;
      else if (a < 0)
        i = s - 1;
      else
        return r;
    }
    return null;
  }
};
function qr(n, t, e) {
  if (t === null || !Array.isArray(n) || !n.length || !B(t))
    return null;
  const i = n[0].programDateTime;
  if (t < (i || 0))
    return null;
  const s = n[n.length - 1].endProgramDateTime;
  if (t >= (s || 0))
    return null;
  for (let r = 0; r < n.length; ++r) {
    const a = n[r];
    if (Xr(t, e, a))
      return a;
  }
  return null;
}
function Ze(n, t, e = 0, i = 0, s = 5e-3) {
  let r = null;
  if (n) {
    r = t[1 + n.sn - t[0].sn] || null;
    const o = n.endDTS - e;
    o > 0 && o < 15e-7 && (e += 15e-7), r && n.level !== r.level && r.end <= n.end && (r = t[2 + n.sn - t[0].sn] || null);
  } else e === 0 && t[0].start === 0 && (r = t[0]);
  if (r && ((!n || n.level === r.level) && yi(e, i, r) === 0 || zr(r, n, Math.min(s, i))))
    return r;
  const a = Ss.search(t, yi.bind(null, e, i));
  return a && (a !== n || !r) ? a : r;
}
function zr(n, t, e) {
  if (t && t.start === 0 && t.level < n.level && (t.endPTS || 0) > 0) {
    const i = t.tagList.reduce((s, r) => (r[0] === "INF" && (s += parseFloat(r[1])), s), e);
    return n.start <= i;
  }
  return !1;
}
function yi(n = 0, t = 0, e) {
  if (e.start <= n && e.start + e.duration > n)
    return 0;
  const i = Math.min(t, e.duration + (e.deltaPTS ? e.deltaPTS : 0));
  return e.start + e.duration - i <= n ? 1 : e.start - i > n && e.start ? -1 : 0;
}
function Xr(n, t, e) {
  const i = Math.min(t, e.duration + (e.deltaPTS ? e.deltaPTS : 0)) * 1e3;
  return (e.endProgramDateTime || 0) - i > n;
}
function Qr(n, t, e) {
  if (n && n.startCC <= t && n.endCC >= t) {
    let i = n.fragments;
    const {
      fragmentHint: s
    } = n;
    s && (i = i.concat(s));
    let r;
    return Ss.search(i, (a) => a.cc < t ? 1 : a.cc > t ? -1 : (r = a, a.end <= e ? 1 : a.start > e ? -1 : 0)), r || null;
  }
  return null;
}
function ge(n) {
  switch (n.details) {
    case D.FRAG_LOAD_TIMEOUT:
    case D.KEY_LOAD_TIMEOUT:
    case D.LEVEL_LOAD_TIMEOUT:
    case D.MANIFEST_LOAD_TIMEOUT:
      return !0;
  }
  return !1;
}
function Ls(n) {
  return n.details.startsWith("key");
}
function As(n) {
  return Ls(n) && !!n.frag && !n.frag.decryptdata;
}
function Ti(n, t) {
  const e = ge(t);
  return n.default[`${e ? "timeout" : "error"}Retry`];
}
function Je(n, t) {
  const e = n.backoff === "linear" ? 1 : Math.pow(2, t);
  return Math.min(e * n.retryDelayMs, n.maxRetryDelayMs);
}
function xi(n) {
  return ct(ct({}, n), {
    errorRetry: null,
    timeoutRetry: null
  });
}
function me(n, t, e, i) {
  if (!n)
    return !1;
  const s = i?.code, r = t < n.maxNumRetry && (Zr(s) || !!e);
  return n.shouldRetry ? n.shouldRetry(n, t, e, i, r) : r;
}
function Zr(n) {
  return Ve(n) || !!n && (n < 400 || n > 499);
}
function Ve(n) {
  return n === 0 && navigator.onLine === !1;
}
var at = {
  DoNothing: 0,
  SendAlternateToPenaltyBox: 2,
  RemoveAlternatePermanently: 3,
  RetryRequest: 5
}, ut = {
  None: 0,
  MoveAllAlternatesMatchingHost: 1,
  MoveAllAlternatesMatchingHDCP: 2,
  MoveAllAlternatesMatchingKey: 4
};
class Jr extends Rt {
  constructor(t) {
    super("error-controller", t.logger), this.hls = void 0, this.playlistError = 0, this.hls = t, this.registerListeners();
  }
  registerListeners() {
    const t = this.hls;
    t.on(E.ERROR, this.onError, this), t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.LEVEL_UPDATED, this.onLevelUpdated, this);
  }
  unregisterListeners() {
    const t = this.hls;
    t && (t.off(E.ERROR, this.onError, this), t.off(E.ERROR, this.onErrorOut, this), t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.LEVEL_UPDATED, this.onLevelUpdated, this));
  }
  destroy() {
    this.unregisterListeners(), this.hls = null;
  }
  startLoad(t) {
  }
  stopLoad() {
    this.playlistError = 0;
  }
  getVariantLevelIndex(t) {
    return t?.type === W.MAIN ? t.level : this.getVariantIndex();
  }
  getVariantIndex() {
    var t;
    const e = this.hls, i = e.currentLevel;
    return (t = e.loadLevelObj) != null && t.details || i === -1 ? e.loadLevel : i;
  }
  variantHasKey(t, e) {
    if (t) {
      var i;
      if ((i = t.details) != null && i.hasKey(e))
        return !0;
      const s = t.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(e);
        });
    }
    return !1;
  }
  onManifestLoading() {
    this.playlistError = 0;
  }
  onLevelUpdated() {
    this.playlistError = 0;
  }
  onError(t, e) {
    var i;
    if (e.fatal)
      return;
    const s = this.hls, r = e.context;
    switch (e.details) {
      case D.FRAG_LOAD_ERROR:
      case D.FRAG_LOAD_TIMEOUT:
      case D.KEY_LOAD_ERROR:
      case D.KEY_LOAD_TIMEOUT:
        e.errorAction = this.getFragRetryOrSwitchAction(e);
        return;
      case D.FRAG_PARSING_ERROR:
        if ((i = e.frag) != null && i.gap) {
          e.errorAction = Wt();
          return;
        }
      // falls through
      case D.FRAG_GAP:
      case D.FRAG_DECRYPT_ERROR: {
        e.errorAction = this.getFragRetryOrSwitchAction(e), e.errorAction.action = at.SendAlternateToPenaltyBox;
        return;
      }
      case D.LEVEL_EMPTY_ERROR:
      case D.LEVEL_PARSING_ERROR:
        {
          var a;
          const u = e.parent === W.MAIN ? e.level : s.loadLevel;
          e.details === D.LEVEL_EMPTY_ERROR && ((a = e.context) != null && (a = a.levelDetails) != null && a.live) ? e.errorAction = this.getPlaylistRetryOrSwitchAction(e, u) : (e.levelRetry = !1, e.errorAction = this.getLevelSwitchAction(e, u));
        }
        return;
      case D.LEVEL_LOAD_ERROR:
      case D.LEVEL_LOAD_TIMEOUT:
        typeof r?.level == "number" && (e.errorAction = this.getPlaylistRetryOrSwitchAction(e, r.level));
        return;
      case D.AUDIO_TRACK_LOAD_ERROR:
      case D.AUDIO_TRACK_LOAD_TIMEOUT:
      case D.SUBTITLE_LOAD_ERROR:
      case D.SUBTITLE_TRACK_LOAD_TIMEOUT:
        if (r) {
          const u = s.loadLevelObj;
          if (u && (r.type === X.AUDIO_TRACK && u.hasAudioGroup(r.groupId) || r.type === X.SUBTITLE_TRACK && u.hasSubtitleGroup(r.groupId))) {
            e.errorAction = this.getPlaylistRetryOrSwitchAction(e, s.loadLevel), e.errorAction.action = at.SendAlternateToPenaltyBox, e.errorAction.flags = ut.MoveAllAlternatesMatchingHost;
            return;
          }
        }
        return;
      case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
        e.errorAction = {
          action: at.SendAlternateToPenaltyBox,
          flags: ut.MoveAllAlternatesMatchingHDCP
        };
        return;
      case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:
      case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:
      case D.KEY_SYSTEM_NO_SESSION:
        e.errorAction = {
          action: at.SendAlternateToPenaltyBox,
          flags: ut.MoveAllAlternatesMatchingKey
        };
        return;
      case D.BUFFER_ADD_CODEC_ERROR:
      case D.REMUX_ALLOC_ERROR:
      case D.BUFFER_APPEND_ERROR:
        if (!e.errorAction) {
          var o;
          e.errorAction = this.getLevelSwitchAction(e, (o = e.level) != null ? o : s.loadLevel);
        }
        return;
      case D.INTERNAL_EXCEPTION:
      case D.BUFFER_APPENDING_ERROR:
      case D.BUFFER_FULL_ERROR:
      case D.LEVEL_SWITCH_ERROR:
      case D.BUFFER_STALLED_ERROR:
      case D.BUFFER_SEEK_OVER_HOLE:
      case D.BUFFER_NUDGE_ON_STALL:
        e.errorAction = Wt();
        return;
    }
    e.type === Y.KEY_SYSTEM_ERROR && (e.levelRetry = !1, e.errorAction = Wt());
  }
  getPlaylistRetryOrSwitchAction(t, e) {
    const i = this.hls, s = Ti(i.config.playlistLoadPolicy, t), r = this.playlistError++;
    if (me(s, r, ge(t), t.response))
      return {
        action: at.RetryRequest,
        flags: ut.None,
        retryConfig: s,
        retryCount: r
      };
    const o = this.getLevelSwitchAction(t, e);
    return s && (o.retryConfig = s, o.retryCount = r), o;
  }
  getFragRetryOrSwitchAction(t) {
    const e = this.hls, i = this.getVariantLevelIndex(t.frag), s = e.levels[i], {
      fragLoadPolicy: r,
      keyLoadPolicy: a
    } = e.config, o = Ti(Ls(t) ? a : r, t), u = e.levels.reduce((d, h) => d + h.fragmentError, 0);
    if (s && (t.details !== D.FRAG_GAP && s.fragmentError++, !As(t) && me(o, u, ge(t), t.response)))
      return {
        action: at.RetryRequest,
        flags: ut.None,
        retryConfig: o,
        retryCount: u
      };
    const l = this.getLevelSwitchAction(t, i);
    return o && (l.retryConfig = o, l.retryCount = u), l;
  }
  getLevelSwitchAction(t, e) {
    const i = this.hls;
    e == null && (e = i.loadLevel);
    const s = this.hls.levels[e];
    if (s) {
      var r, a;
      const l = t.details;
      s.loadError++, l === D.BUFFER_APPEND_ERROR && s.fragmentError++;
      let d = -1;
      const {
        levels: h,
        loadLevel: c,
        minAutoLevel: f,
        maxAutoLevel: g
      } = i;
      !i.autoLevelEnabled && !i.config.preserveManualLevelOnError && (i.loadLevel = -1);
      const p = (r = t.frag) == null ? void 0 : r.type, y = (p === W.AUDIO && l === D.FRAG_PARSING_ERROR || t.sourceBufferName === "audio" && (l === D.BUFFER_ADD_CODEC_ERROR || l === D.BUFFER_APPEND_ERROR)) && h.some(({
        audioCodec: C
      }) => s.audioCodec !== C), v = t.sourceBufferName === "video" && (l === D.BUFFER_ADD_CODEC_ERROR || l === D.BUFFER_APPEND_ERROR) && h.some(({
        codecSet: C,
        audioCodec: S
      }) => s.codecSet !== C && s.audioCodec === S), {
        type: x,
        groupId: A
      } = (a = t.context) != null ? a : {};
      for (let C = h.length; C--; ) {
        const S = (C + c) % h.length;
        if (S !== c && S >= f && S <= g && h[S].loadError === 0) {
          var o, u;
          const R = h[S];
          if (l === D.FRAG_GAP && p === W.MAIN && t.frag) {
            const b = h[S].details;
            if (b) {
              const I = Ze(t.frag, b.fragments, t.frag.start);
              if (I != null && I.gap)
                continue;
            }
          } else {
            if (x === X.AUDIO_TRACK && R.hasAudioGroup(A) || x === X.SUBTITLE_TRACK && R.hasSubtitleGroup(A))
              continue;
            if (p === W.AUDIO && (o = s.audioGroups) != null && o.some((b) => R.hasAudioGroup(b)) || p === W.SUBTITLE && (u = s.subtitleGroups) != null && u.some((b) => R.hasSubtitleGroup(b)) || y && s.audioCodec === R.audioCodec || v && s.codecSet === R.codecSet || !y && s.codecSet !== R.codecSet)
              continue;
          }
          d = S;
          break;
        }
      }
      if (d > -1 && i.loadLevel !== d)
        return t.levelRetry = !0, this.playlistError = 0, {
          action: at.SendAlternateToPenaltyBox,
          flags: ut.None,
          nextAutoLevel: d
        };
    }
    return {
      action: at.SendAlternateToPenaltyBox,
      flags: ut.MoveAllAlternatesMatchingHost
    };
  }
  onErrorOut(t, e) {
    var i;
    switch ((i = e.errorAction) == null ? void 0 : i.action) {
      case at.DoNothing:
        break;
      case at.SendAlternateToPenaltyBox:
        this.sendAlternateToPenaltyBox(e), !e.errorAction.resolved && e.details !== D.FRAG_GAP ? e.fatal = !0 : /MediaSource readyState: ended/.test(e.error.message) && (this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`), this.hls.recoverMediaError());
        break;
    }
    if (e.fatal) {
      this.hls.stopLoad();
      return;
    }
  }
  sendAlternateToPenaltyBox(t) {
    const e = this.hls, i = t.errorAction;
    if (!i)
      return;
    const {
      flags: s
    } = i, r = i.nextAutoLevel;
    switch (s) {
      case ut.None:
        this.switchLevel(t, r);
        break;
      case ut.MoveAllAlternatesMatchingHDCP: {
        const u = this.getVariantLevelIndex(t.frag), l = e.levels[u], d = l?.attrs["HDCP-LEVEL"];
        if (i.hdcpLevel = d, d === "NONE")
          this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");
        else if (d) {
          e.maxHdcpLevel = Ge[Ge.indexOf(d) - 1], i.resolved = !0, this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);
          break;
        }
      }
      // eslint-disable-next-line no-fallthrough
      case ut.MoveAllAlternatesMatchingKey: {
        const u = t.decryptdata;
        if (u) {
          const l = this.hls.levels, d = l.length;
          for (let c = d; c--; )
            if (this.variantHasKey(l[c], u)) {
              var a, o;
              this.log(`Banned key found in level ${c} (${l[c].bitrate}bps) or audio group "${(a = l[c].audioGroups) == null ? void 0 : a.join(",")}" (${(o = t.frag) == null ? void 0 : o.type} fragment) ${qt(u.keyId || [])}`), l[c].fragmentError++, l[c].loadError++, this.log(`Removing level ${c} with key error (${t.error})`), this.hls.removeLevel(c);
            }
          const h = t.frag;
          if (this.hls.levels.length < d)
            i.resolved = !0;
          else if (h && h.type !== W.MAIN) {
            const c = h.decryptdata;
            c && !u.matches(c) && (i.resolved = !0);
          }
        }
        break;
      }
    }
    i.resolved || this.switchLevel(t, r);
  }
  switchLevel(t, e) {
    if (e !== void 0 && t.errorAction && (this.warn(`switching to level ${e} after ${t.details}`), this.hls.nextAutoLevel = e, t.errorAction.resolved = !0, this.hls.nextLoadLevel = this.hls.nextAutoLevel, t.details === D.BUFFER_ADD_CODEC_ERROR && t.mimeType && t.sourceBufferName !== "audiovideo")) {
      const i = Ue(t.mimeType), s = this.hls.levels;
      for (let r = s.length; r--; )
        s[r][`${t.sourceBufferName}Codec`] === i && (this.log(`Removing level ${r} for ${t.details} ("${i}" not supported)`), this.hls.removeLevel(r));
    }
  }
}
function Wt(n) {
  const t = {
    action: at.DoNothing,
    flags: ut.None
  };
  return n && (t.resolved = !0), t;
}
const tn = /^(\d+)x(\d+)$/, Si = /(.+?)=(".*?"|.*?)(?:,|$)/g;
class it {
  constructor(t, e) {
    typeof t == "string" && (t = it.parseAttrList(t, e)), nt(this, t);
  }
  get clientAttrs() {
    return Object.keys(this).filter((t) => t.substring(0, 2) === "X-");
  }
  decimalInteger(t) {
    const e = parseInt(this[t], 10);
    return e > Number.MAX_SAFE_INTEGER ? 1 / 0 : e;
  }
  hexadecimalInteger(t) {
    if (this[t]) {
      let e = (this[t] || "0x").slice(2);
      e = (e.length & 1 ? "0" : "") + e;
      const i = new Uint8Array(e.length / 2);
      for (let s = 0; s < e.length / 2; s++)
        i[s] = parseInt(e.slice(s * 2, s * 2 + 2), 16);
      return i;
    }
    return null;
  }
  hexadecimalIntegerAsNumber(t) {
    const e = parseInt(this[t], 16);
    return e > Number.MAX_SAFE_INTEGER ? 1 / 0 : e;
  }
  decimalFloatingPoint(t) {
    return parseFloat(this[t]);
  }
  optionalFloat(t, e) {
    const i = this[t];
    return i ? parseFloat(i) : e;
  }
  enumeratedString(t) {
    return this[t];
  }
  enumeratedStringList(t, e) {
    const i = this[t];
    return (i ? i.split(/[ ,]+/) : []).reduce((s, r) => (s[r.toLowerCase()] = !0, s), e);
  }
  bool(t) {
    return this[t] === "YES";
  }
  decimalResolution(t) {
    const e = tn.exec(this[t]);
    if (e !== null)
      return {
        width: parseInt(e[1], 10),
        height: parseInt(e[2], 10)
      };
  }
  static parseAttrList(t, e) {
    let i;
    const s = {};
    for (Si.lastIndex = 0; (i = Si.exec(t)) !== null; ) {
      const a = i[1].trim();
      let o = i[2];
      const u = o.indexOf('"') === 0 && o.lastIndexOf('"') === o.length - 1;
      let l = !1;
      if (u)
        o = o.slice(1, -1);
      else
        switch (a) {
          case "IV":
          case "SCTE35-CMD":
          case "SCTE35-IN":
          case "SCTE35-OUT":
            l = !0;
        }
      if (!(e && (u || l))) {
        if (!l && !u)
          switch (a) {
            case "CLOSED-CAPTIONS":
              if (o === "NONE")
                break;
            // falls through
            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":
              J.warn(`${t}: attribute ${a} is missing quotes`);
          }
      }
      s[a] = o;
    }
    return s;
  }
}
const en = "com.apple.hls.interstitial";
function sn(n) {
  return n !== "ID" && n !== "CLASS" && n !== "CUE" && n !== "START-DATE" && n !== "DURATION" && n !== "END-DATE" && n !== "END-ON-NEXT";
}
function rn(n) {
  return n === "SCTE35-OUT" || n === "SCTE35-IN" || n === "SCTE35-CMD";
}
class Rs {
  constructor(t, e, 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 = e?.tagAnchor || null, this.tagOrder = (s = e?.tagOrder) != null ? s : i, e) {
      const r = e.attr;
      for (const a in r)
        if (Object.prototype.hasOwnProperty.call(t, a) && t[a] !== r[a]) {
          J.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${t.ID}"`), this._badValueForSameId = a;
          break;
        }
      t = nt(new it({}), r, t);
    }
    if (this.attr = t, e ? (this._startDate = e._startDate, this._cue = e._cue, this._endDate = e._endDate, this._dateAtEnd = e._dateAtEnd) : this._startDate = new Date(t["START-DATE"]), "END-DATE" in this.attr) {
      const r = e?.endDate || new Date(this.attr["END-DATE"]);
      B(r.getTime()) && (this._endDate = r);
    }
  }
  get id() {
    return this.attr.ID;
  }
  get class() {
    return this.attr.CLASS;
  }
  get cue() {
    const t = this._cue;
    return t === void 0 ? this._cue = this.attr.enumeratedStringList(this.attr.CUE ? "CUE" : "X-CUE", {
      pre: !1,
      post: !1,
      once: !1
    }) : t;
  }
  get startTime() {
    const {
      tagAnchor: t
    } = this;
    return t === null || t.programDateTime === null ? (J.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`), NaN) : t.start + (this.startDate.getTime() - t.programDateTime) / 1e3;
  }
  get startDate() {
    return this._startDate;
  }
  get endDate() {
    const t = this._endDate || this._dateAtEnd;
    if (t)
      return t;
    const e = this.duration;
    return e !== null ? this._dateAtEnd = new Date(this._startDate.getTime() + e * 1e3) : null;
  }
  get duration() {
    if ("DURATION" in this.attr) {
      const t = this.attr.decimalFloatingPoint("DURATION");
      if (B(t))
        return t;
    } 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 === en;
  }
  get isValid() {
    return !!this.id && !this._badValueForSameId && B(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 nn = 10;
class an {
  constructor(t) {
    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 = t;
  }
  reloaded(t) {
    if (!t) {
      this.advanced = !0, this.updated = !0;
      return;
    }
    const e = this.lastPartSn - t.lastPartSn, i = this.lastPartIndex - t.lastPartIndex;
    this.updated = this.endSN !== t.endSN || !!i || !!e || !this.live, this.advanced = this.endSN > t.endSN || e > 0 || e === 0 && i > 0, this.updated || this.advanced ? this.misses = Math.floor(t.misses * 0.6) : this.misses = t.misses + 1;
  }
  hasKey(t) {
    return this.encryptedFragments.some((e) => {
      let i = e.decryptdata;
      return i || (e.setKeyFormat(t.keyFormat), i = e.decryptdata), !!i && t.matches(i);
    });
  }
  get hasProgramDateTime() {
    return this.fragments.length ? B(this.fragments[this.fragments.length - 1].programDateTime) : !1;
  }
  get levelTargetDuration() {
    return this.averagetargetduration || this.targetduration || nn;
  }
  get drift() {
    const t = this.driftEndTime - this.driftStartTime;
    return t > 0 ? (this.driftEnd - this.driftStart) * 1e3 / t : 1;
  }
  get edge() {
    return this.partEnd || this.fragmentEnd;
  }
  get partEnd() {
    var t;
    return (t = this.partList) != null && t.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 t;
    return (t = this.partList) != null && t.length ? this.partList[this.partList.length - 1].index : -1;
  }
  get maxPartIndex() {
    const t = this.partList;
    if (t) {
      const e = this.lastPartIndex;
      if (e !== -1) {
        for (let i = t.length; i--; )
          if (t[i].index > e)
            return t[i].index;
        return e;
      }
    }
    return 0;
  }
  get lastPartSn() {
    var t;
    return (t = this.partList) != null && t.length ? this.partList[this.partList.length - 1].fragment.sn : this.endSN;
  }
  get expired() {
    if (this.live && this.age && this.misses < 3) {
      const t = this.partEnd - this.fragmentStart;
      return this.age > Math.max(t, this.totalduration) + this.levelTargetDuration;
    }
    return !1;
  }
}
function bs(n, t) {
  return n.length === t.length ? !n.some((e, i) => e !== t[i]) : !1;
}
function Li(n, t) {
  return !n && !t ? !0 : !n || !t ? !1 : bs(n, t);
}
var Pt = {
  cbc: 0,
  ctr: 1
};
function Yt(n) {
  return n === "AES-128" || n === "AES-256" || n === "AES-256-CTR";
}
function Is(n) {
  switch (n) {
    case "AES-128":
    case "AES-256":
      return Pt.cbc;
    case "AES-256-CTR":
      return Pt.ctr;
    default:
      throw new Error(`invalid full segment method ${n}`);
  }
}
let Ai = {};
class ye {
  static clearKeyUriToKeyIdMap() {
    Ai = {};
  }
  static setKeyIdForUri(t, e) {
    Ai[t] = e;
  }
  constructor(t, e, i, s = [1], r = 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 = t, this.uri = e, this.keyFormat = i, this.keyFormatVersions = s, this.iv = r, this.encrypted = t ? t !== "NONE" : !1, this.isCommonEncryption = this.encrypted && !Yt(t), a != null && a.startsWith("0x") && (this.keyId = new Uint8Array(us(a)));
  }
  matches(t) {
    return t.uri === this.uri && t.method === this.method && t.encrypted === this.encrypted && t.keyFormat === this.keyFormat && bs(t.keyFormatVersions, this.keyFormatVersions) && Li(t.iv, this.iv) && Li(t.keyId, this.keyId);
  }
  isSupported() {
    if (this.method) {
      if (Yt(this.method) || this.method === "NONE")
        return !0;
      if (this.keyFormat === "identity")
        return this.method === "SAMPLE-AES";
    }
    return !1;
  }
  getDecryptData(t, e) {
    if (!this.encrypted || !this.uri)
      return null;
    if (Yt(this.method)) {
      let i = this.iv;
      return i || (typeof t != "number" && (J.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`), t = 0), i = on(t)), new ye(this.method, this.uri, "identity", this.keyFormatVersions, i);
    }
    return this;
  }
}
function on(n) {
  const t = new Uint8Array(16);
  for (let e = 12; e < 16; e++)
    t[e] = n >> 8 * (15 - e) & 255;
  return t;
}
const Ri = /#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, bi = /#EXT-X-MEDIA:(.*)/g, ln = /^#EXT(?:INF|-X-TARGETDURATION):/m, be = 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"), un = 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 Tt {
  static findGroup(t, e) {
    for (let i = 0; i < t.length; i++) {
      const s = t[i];
      if (s.id === e)
        return s;
    }
  }
  static resolve(t, e) {
    return je.buildAbsoluteURL(e, t, {
      alwaysNormalize: !0
    });
  }
  static isMediaPlaylist(t) {
    return ln.test(t);
  }
  static parseMasterPlaylist(t, e) {
    const s = {
      contentSteering: null,
      levels: [],
      playlistParsingError: null,
      sessionData: null,
      sessionKeys: null,
      startTimeOffset: null,
      variableList: null,
      hasVariableRefs: !1
    }, r = [];
    if (Ri.lastIndex = 0, !t.startsWith("#EXTM3U"))
      return s.playlistParsingError = new Error("no EXTM3U delimiter"), s;
    let a;
    for (; (a = Ri.exec(t)) != null; )
      if (a[1]) {
        var o;
        const l = new it(a[1], s), d = a[2], h = {
          attrs: l,
          bitrate: l.decimalInteger("BANDWIDTH") || l.decimalInteger("AVERAGE-BANDWIDTH"),
          name: l.NAME,
          url: Tt.resolve(d, e)
        }, c = l.decimalResolution("RESOLUTION");
        c && (h.width = c.width, h.height = c.height), Ci(l.CODECS, h);
        const f = l["SUPPLEMENTAL-CODECS"];
        f && (h.supplemental = {}, Ci(f, h.supplemental)), (o = h.unknownCodecs) != null && o.length || r.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 it(d, s), c = h["DATA-ID"];
            c && (s.sessionData === null && (s.sessionData = {}), s.sessionData[c] = h);
            break;
          }
          case "SESSION-KEY": {
            const h = Ii(d, e, s);
            h.encrypted && h.isSupported() ? (s.sessionKeys === null && (s.sessionKeys = []), s.sessionKeys.push(h)) : J.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);
            break;
          }
          case "DEFINE":
            break;
          case "CONTENT-STEERING": {
            const h = new it(d, s);
            s.contentSteering = {
              uri: Tt.resolve(h["SERVER-URI"], e),
              pathwayId: h["PATHWAY-ID"] || "."
            };
            break;
          }
          case "START": {
            s.startTimeOffset = Di(d);
            break;
          }
        }
      }
    const u = r.length > 0 && r.length < s.levels.length;
    return s.levels = u ? r : s.levels, s.levels.length === 0 && (s.playlistParsingError = new Error("no levels found in manifest")), s;
  }
  static parseMasterPlaylistMedia(t, e, i) {
    let s;
    const r = {}, 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 u = 0;
    for (bi.lastIndex = 0; (s = bi.exec(t)) !== null; ) {
      const l = new it(s[1], i), d = l.TYPE;
      if (d) {
        const h = o[d], c = r[d] || [];
        r[d] = c;
        const f = l.LANGUAGE, g = l["ASSOC-LANGUAGE"], p = l.CHANNELS, m = l.CHARACTERISTICS, y = l["INSTREAM-ID"], T = {
          attrs: l,
          bitrate: 0,
          id: u++,
          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 ? Tt.resolve(l.URI, e) : ""
        };
        if (g && (T.assocLang = g), p && (T.channels = p), m && (T.characteristics = m), y && (T.instreamId = y), h != null && h.length) {
          const v = Tt.findGroup(h, T.groupId) || h[0];
          _i(T, v, "audioCodec"), _i(T, v, "textCodec");
        }
        c.push(T);
      }
    }
    return r;
  }
  static parseLevelPlaylist(t, e, i, s, r, a) {
    var o;
    const u = {
      url: e
    }, l = new an(e), d = l.fragments, h = [];
    let c = null, f = 0, g = 0, p = 0, m = 0, y = 0, T = null, v = new Le(s, u), x, A, C, S = -1, R = !1, b = null, I;
    if (be.lastIndex = 0, l.m3u8 = t, l.hasVariableRefs = !1, ((o = be.exec(t)) == null ? void 0 : o[0]) !== "#EXTM3U")
      return l.playlistParsingError = new Error("Missing format identifier #EXTM3U"), l;
    for (; (x = be.exec(t)) !== null; ) {
      R && (R = !1, v = new Le(s, u), v.playlistOffset = p, v.setStart(p), v.sn = f, v.cc = m, y && (v.bitrate = y), v.level = i, c && (v.initSegment = c, c.rawProgramDateTime && (v.rawProgramDateTime = c.rawProgramDateTime, c.rawProgramDateTime = null), b && (v.setByteRange(b), b = null)));
      const V = x[1];
      if (V) {
        v.duration = parseFloat(V);
        const N = (" " + x[2]).slice(1);
        v.title = N || null, v.tagList.push(N ? ["INF", V, N] : ["INF", V]);
      } else if (x[3]) {
        if (B(v.duration)) {
          v.playlistOffset = p, v.setStart(p), C && ki(v, C, l), v.sn = f, v.level = i, v.cc = m, d.push(v);
          const N = (" " + x[3]).slice(1);
          v.relurl = N, He(v, T, h), T = v, p += v.duration, f++, g = 0, R = !0;
        }
      } else {
        if (x = x[0].match(un), !x) {
          J.warn("No matches on slow regex match for level playlist!");
          continue;
        }
        for (A = 1; A < x.length && x[A] === void 0; A++)
          ;
        const N = (" " + x[A]).slice(1), P = (" " + x[A + 1]).slice(1), G = x[A + 2] ? (" " + x[A + 2]).slice(1) : null;
        switch (N) {
          case "BYTERANGE":
            T ? v.setByteRange(P, T) : v.setByteRange(P);
            break;
          case "PROGRAM-DATE-TIME":
            v.rawProgramDateTime = P, v.tagList.push(["PROGRAM-DATE-TIME", P]), S === -1 && (S = d.length);
            break;
          case "PLAYLIST-TYPE":
            l.type && St(l, N, x), l.type = P.toUpperCase();
            break;
          case "MEDIA-SEQUENCE":
            l.startSN !== 0 ? St(l, N, x) : d.length > 0 && Oi(l, N, x), f = l.startSN = parseInt(P);
            break;
          case "SKIP": {
            l.skippedSegments && St(l, N, x);
            const M = new it(P, l), U = M.decimalInteger("SKIPPED-SEGMENTS");
            if (B(U)) {
              l.skippedSegments += U;
              for (let O = U; O--; )
                d.push(null);
              f += U;
            }
            const H = M.enumeratedString("RECENTLY-REMOVED-DATERANGES");
            H && (l.recentlyRemovedDateranges = (l.recentlyRemovedDateranges || []).concat(H.split("	")));
            break;
          }
          case "TARGETDURATION":
            l.targetduration !== 0 && St(l, N, x), l.targetduration = Math.max(parseInt(P), 1);
            break;
          case "VERSION":
            l.version !== null && St(l, N, x), l.version = parseInt(P);
            break;
          case "INDEPENDENT-SEGMENTS":
            break;
          case "ENDLIST":
            l.live || St(l, N, x), l.live = !1;
            break;
          case "#":
            (P || G) && v.tagList.push(G ? [P, G] : [P]);
            break;
          case "DISCONTINUITY":
            m++, v.tagList.push(["DIS"]);
            break;
          case "GAP":
            v.gap = !0, v.tagList.push([N]);
            break;
          case "BITRATE":
            v.tagList.push([N, P]), y = parseInt(P) * 1e3, B(y) ? v.bitrate = y : y = 0;
            break;
          case "DATERANGE": {
            const M = new it(P, l), U = new Rs(M, l.dateRanges[M.ID], l.dateRangeTagCount);
            l.dateRangeTagCount++, U.isValid || l.skippedSegments ? l.dateRanges[U.id] = U : J.warn(`Ignoring invalid DATERANGE tag: "${P}"`), v.tagList.push(["EXT-X-DATERANGE", P]);
            break;
          }
          case "DEFINE":
            break;
          case "DISCONTINUITY-SEQUENCE":
            l.startCC !== 0 ? St(l, N, x) : d.length > 0 && Oi(l, N, x), l.startCC = m = parseInt(P);
            break;
          case "KEY": {
            const M = Ii(P, e, l);
            if (M.isSupported()) {
              if (M.method === "NONE") {
                C = void 0;
                break;
              }
              C || (C = {});
              const U = C[M.keyFormat];
              U != null && U.matches(M) || (U && (C = nt({}, C)), C[M.keyFormat] = M);
            } else
              J.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${P}" (light build)`);
            break;
          }
          case "START":
            l.startTimeOffset = Di(P);
            break;
          case "MAP": {
            const M = new it(P, l);
            if (v.duration) {
              const U = new Le(s, u);
              Pi(U, M, i, C), c = U, v.initSegment = c, c.rawProgramDateTime && !v.rawProgramDateTime && (v.rawProgramDateTime = c.rawProgramDateTime);
            } else {
              const U = v.byteRangeEndOffset;
              if (U) {
                const H = v.byteRangeStartOffset;
                b = `${U - H}@${H}`;
              } else
                b = null;
              Pi(v, M, i, C), c = v, R = !0;
            }
            c.cc = m;
            break;
          }
          case "SERVER-CONTROL": {
            I && St(l, N, x), I = new it(P), l.canBlockReload = I.bool("CAN-BLOCK-RELOAD"), l.canSkipUntil = I.optionalFloat("CAN-SKIP-UNTIL", 0), l.canSkipDateRanges = l.canSkipUntil > 0 && I.bool("CAN-SKIP-DATERANGES"), l.partHoldBack = I.optionalFloat("PART-HOLD-BACK", 0), l.holdBack = I.optionalFloat("HOLD-BACK", 0);
            break;
          }
          case "PART-INF": {
            l.partTarget && St(l, N, x);
            const M = new it(P);
            l.partTarget = M.decimalFloatingPoint("PART-TARGET");
            break;
          }
          case "PART": {
            let M = l.partList;
            M || (M = l.partList = []);
            const U = g > 0 ? M[M.length - 1] : void 0, H = g++, O = new it(P, l), w = new xr(O, v, u, H, U);
            M.push(w), v.duration += w.duration;
            break;
          }
          case "PRELOAD-HINT": {
            const M = new it(P, l);
            l.preloadHint = M;
            break;
          }
          case "RENDITION-REPORT": {
            const M = new it(P, l);
            l.renditionReports = l.renditionReports || [], l.renditionReports.push(M);
            break;
          }
          default:
            J.warn(`line parsed but not handled: ${x}`);
            break;
        }
      }
    }
    T && !T.relurl ? (d.pop(), p -= T.duration, l.partList && (l.fragmentHint = T)) : l.partList && (He(v, T, h), v.cc = m, l.fragmentHint = v, C && ki(v, C, l)), l.targetduration || (l.playlistParsingError = new Error("Missing Target Duration"));
    const _ = d.length, F = d[0], $ = d[_ - 1];
    if (p += l.skippedSegments * l.targetduration, p > 0 && _ && $) {
      l.averagetargetduration = p / _;
      const V = $.sn;
      l.endSN = V !== "initSegment" ? V : 0, l.live || ($.endList = !0), S > 0 && (hn(d, S), F && h.unshift(F));
    }
    return l.fragmentHint && (p += l.fragmentHint.duration), l.totalduration = p, h.length && l.dateRangeTagCount && F && Ds(h, l), l.endCC = m, l;
  }
}
function Ds(n, t) {
  let e = n.length;
  if (!e)
    if (t.hasProgramDateTime) {
      const o = t.fragments[t.fragments.length - 1];
      n.push(o), e++;
    } else
      return;
  const i = n[e - 1], s = t.live ? 1 / 0 : t.totalduration, r = Object.keys(t.dateRanges);
  for (let o = r.length; o--; ) {
    const u = t.dateRanges[r[o]], l = u.startDate.getTime();
    u.tagAnchor = i.ref;
    for (let d = e; d--; ) {
      var a;
      if (((a = n[d]) == null ? void 0 : a.sn) < t.startSN)
        break;
      const h = dn(t, l, n, d, s);
      if (h !== -1) {
        u.tagAnchor = t.fragments[h].ref;
        break;
      }
    }
  }
}
function dn(n, t, e, i, s) {
  const r = e[i];
  if (r) {
    const o = r.programDateTime;
    if (t >= o || i === 0) {
      var a;
      const u = (((a = e[i + 1]) == null ? void 0 : a.start) || s) - r.start;
      if (t <= o + u * 1e3) {
        const l = e[i].sn - n.startSN;
        if (l < 0)
          return -1;
        const d = n.fragments;
        if (d.length > e.length) {
          const c = (e[i + 1] || d[d.length - 1]).sn - n.startSN;
          for (let f = c; f > l; f--) {
            const g = d[f].programDateTime;
            if (t >= g && t < g + d[f].duration * 1e3)
              return f;
          }
        }
        return l;
      }
    }
  }
  return -1;
}
function Ii(n, t, e) {
  var i, s;
  const r = new it(n, e), a = (i = r.METHOD) != null ? i : "", o = r.URI, u = r.hexadecimalInteger("IV"), l = r.KEYFORMATVERSIONS, d = (s = r.KEYFORMAT) != null ? s : "identity";
  o && r.IV && !u && J.error(`Invalid IV: ${r.IV}`);
  const h = o ? Tt.resolve(o, t) : "", c = (l || "1").split("/").map(Number).filter(Number.isFinite);
  return new ye(a, h, d, c, u, r.KEYID);
}
function Di(n) {
  const e = new it(n).decimalFloatingPoint("TIME-OFFSET");
  return B(e) ? e : null;
}
function Ci(n, t) {
  let e = (n || "").split(/[ ,]+/).filter((i) => i);
  ["video", "audio", "text"].forEach((i) => {
    const s = e.filter((r) => Xe(r, i));
    s.length && (t[`${i}Codec`] = s.map((r) => r.split("/")[0]).join(","), e = e.filter((r) => s.indexOf(r) === -1));
  }), t.unknownCodecs = e;
}
function _i(n, t, e) {
  const i = t[e];
  i && (n[e] = i);
}
function hn(n, t) {
  let e = n[t];
  for (let i = t; i--; ) {
    const s = n[i];
    if (!s)
      return;
    s.programDateTime = e.programDateTime - s.duration * 1e3, e = s;
  }
}
function He(n, t, e) {
  n.rawProgramDateTime ? e.push(n) : t != null && t.programDateTime && (n.programDateTime = t.endProgramDateTime);
}
function Pi(n, t, e, i) {
  n.relurl = t.URI, t.BYTERANGE && n.setByteRange(t.BYTERANGE), n.level = e, n.sn = "initSegment", i && (n.levelkeys = i), n.initSegment = null;
}
function ki(n, t, e) {
  n.levelkeys = t;
  const {
    encryptedFragments: i
  } = e;
  (!i.length || i[i.length - 1].levelkeys !== t) && Object.keys(t).some((s) => t[s].isCommonEncryption) && i.push(n);
}
function St(n, t, e) {
  n.playlistParsingError = new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`);
}
function Oi(n, t, e) {
  n.playlistParsingError = new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`);
}
function Ie(n, t) {
  const e = t.startPTS;
  if (B(e)) {
    let i = 0, s;
    t.sn > n.sn ? (i = e - n.start, s = n) : (i = n.start - e, s = t), s.duration !== i && s.setDuration(i);
  } else t.sn > n.sn ? n.cc === t.cc && n.minEndPTS ? t.setStart(n.start + (n.minEndPTS - n.start)) : t.setStart(n.start + n.duration) : t.setStart(Math.max(n.start - t.duration, 0));
}
function Cs(n, t, e, i, s, r, a) {
  i - e <= 0 && (a.warn("Fragment should have a positive duration", t), i = e + t.duration, r = s + t.duration);
  let u = e, l = i;
  const d = t.startPTS, h = t.endPTS;
  if (B(d)) {
    const y = Math.abs(d - e);
    n && y > n.totalduration ? a.warn(`media timestamps and playlist times differ by ${y}s for level ${t.level} ${n.url}`) : B(t.deltaPTS) ? t.deltaPTS = Math.max(y, t.deltaPTS) : t.deltaPTS = y, u = Math.max(e, d), e = Math.min(e, d), s = t.startDTS !== void 0 ? Math.min(s, t.startDTS) : s, l = Math.min(i, h), i = Math.max(i, h), r = t.endDTS !== void 0 ? Math.max(r, t.endDTS) : r;
  }
  const c = e - t.start;
  t.start !== 0 && t.setStart(e), t.setDuration(i - t.start), t.startPTS = e, t.maxStartPTS = u, t.startDTS = s, t.endPTS = i, t.minEndPTS = l, t.endDTS = r;
  const f = t.sn;
  if (!n || f < n.startSN || f > n.endSN)
    return 0;
  let g;
  const p = f - n.startSN, m = n.fragments;
  for (m[p] = t, g = p; g > 0; g--)
    Ie(m[g], m[g - 1]);
  for (g = p; g < m.length - 1; g++)
    Ie(m[g], m[g + 1]);
  return n.fragmentHint && Ie(m[m.length - 1], n.fragmentHint), n.PTSKnown = n.alignedSliding = !0, c;
}
function cn(n, t, e) {
  if (n === t)
    return;
  let i = null;
  const s = n.fragments;
  for (let d = s.length - 1; d >= 0; d--) {
    const h = s[d].initSegment;
    if (h) {
      i = h;
      break;
    }
  }
  n.fragmentHint && delete n.fragmentHint.endPTS;
  let r;
  mn(n, t, (d, h, c, f) => {
    if ((!t.startCC || t.skippedSegments) && h.cc !== d.cc) {
      const g = d.cc - h.cc;
      for (let p = c; p < f.length; p++)
        f[p].cc += g;
      t.endCC = f[f.length - 1].cc;
    }
    B(d.startPTS) && B(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 && (r = h), t.PTSKnown = t.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 = t.fragments, o = t.fragmentHint ? a.concat(t.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);
  }), t.skippedSegments) {
    if (t.deltaUpdateFailed = a.some((d) => !d), t.deltaUpdateFailed) {
      e.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");
      for (let d = t.skippedSegments; d--; )
        a.shift();
      t.startSN = a[0].sn;
    } else {
      t.canSkipDateRanges && (t.dateRanges = fn(n.dateRanges, t, e));
      const d = n.fragments.filter((h) => h.rawProgramDateTime);
      if (n.hasProgramDateTime && !t.hasProgramDateTime)
        for (let h = 1; h < o.length; h++)
          o[h].programDateTime === null && He(o[h], o[h - 1], d);
      Ds(d, t);
    }
    t.endCC = a[a.length - 1].cc;
  }
  if (!t.startCC) {
    var u;
    const d = ks(n, t.startSN - 1);
    t.startCC = (u = d?.cc) != null ? u : a[0].cc;
  }
  gn(n.partList, t.partList, (d, h) => {
    h.elementaryStreams = d.elementaryStreams, h.stats = d.stats;
  }), r ? Cs(t, r, r.startPTS, r.endPTS, r.startDTS, r.endDTS, e) : _s(n, t), a.length && (t.totalduration = t.edge - a[0].start), t.driftStartTime = n.driftStartTime, t.driftStart = n.driftStart;
  const l = t.advancedDateTime;
  if (t.advanced && l) {
    const d = t.edge;
    t.driftStart || (t.driftStartTime = l, t.driftStart = d), t.driftEndTime = l, t.driftEnd = d;
  } else
    t.driftEndTime = n.driftEndTime, t.driftEnd = n.driftEnd, t.advancedDateTime = n.advancedDateTime;
  t.requestScheduled === -1 && (t.requestScheduled = n.requestScheduled);
}
function fn(n, t, e) {
  const {
    dateRanges: i,
    recentlyRemovedDateranges: s
  } = t, r = nt({}, n);
  s && s.forEach((u) => {
    delete r[u];
  });
  const o = Object.keys(r).length;
  return o ? (Object.keys(i).forEach((u) => {
    const l = r[u], d = new Rs(i[u].attr, l);
    d.isValid ? (r[u] = d, l || (d.tagOrder += o)) : e.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ot(i[u].attr)}"`);
  }), r) : i;
}
function gn(n, t, e) {
  if (n && t) {
    let i = 0;
    for (let s = 0, r = n.length; s <= r; s++) {
      const a = n[s], o = t[s + i];
      a && o && a.index === o.index && a.fragment.sn === o.fragment.sn ? e(a, o) : i--;
    }
  }
}
function mn(n, t, e) {
  const i = t.skippedSegments, s = Math.max(n.startSN, t.startSN) - t.startSN, r = (n.fragmentHint ? 1 : 0) + (i ? t.endSN : Math.min(n.endSN, t.endSN)) - t.startSN, a = t.startSN - n.startSN, o = t.fragmentHint ? t.fragments.concat(t.fragmentHint) : t.fragments, u = n.fragmentHint ? n.fragments.concat(n.fragmentHint) : n.fragments;
  for (let l = s; l <= r; l++) {
    const d = u[a + l];
    let h = o[l];
    if (i && !h && d && (h = t.fragments[l] = d), d && h) {
      e(d, h, l, o);
      const c = d.relurl, f = h.relurl;
      if (c && En(c, f)) {
        t.playlistParsingError = wi(`media sequence mismatch ${h.sn}:`, n, t, d, h);
        return;
      } else if (d.cc !== h.cc) {
        t.playlistParsingError = wi(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`, n, t, d, h);
        return;
      }
    }
  }
}
function wi(n, t, e, i, s) {
  return new Error(`${n} ${s.url}
Playlist starting @${t.startSN}
${t.m3u8}

Playlist starting @${e.startSN}
${e.m3u8}`);
}
function _s(n, t, e = !0) {
  const i = t.startSN + t.skippedSegments - n.startSN, s = n.fragments, r = i >= 0;
  let a = 0;
  if (r && i < s.length)
    a = s[i].start;
  else if (r && t.startSN === n.endSN + 1)
    a = n.fragmentEnd;
  else if (r && e)
    a = n.fragmentStart + i * t.levelTargetDuration;
  else if (!t.skippedSegments && t.fragmentStart === 0)
    a = n.fragmentStart;
  else
    return;
  pn(t, a);
}
function pn(n, t) {
  if (t) {
    const e = n.fragments;
    for (let i = n.skippedSegments; i < e.length; i++)
      e[i].addStart(t);
    n.fragmentHint && n.fragmentHint.addStart(t);
  }
}
function Ps(n, t = 1 / 0) {
  let e = 1e3 * n.targetduration;
  if (n.updated) {
    const i = n.fragments;
    if (i.length && e * 4 > t) {
      const r = i[i.length - 1].duration * 1e3;
      r < e && (e = r);
    }
  } else
    e /= 2;
  return Math.round(e);
}
function ks(n, t, e) {
  if (!n)
    return null;
  let i = n.fragments[t - n.startSN];
  return i || (i = n.fragmentHint, i && i.sn === t) ? i : t < n.startSN && e && e.sn === t ? e : null;
}
function Fi(n, t, e) {
  return n ? Os(n.partList, t, e) : null;
}
function Os(n, t, e) {
  if (n)
    for (let i = n.length; i--; ) {
      const s = n[i];
      if (s.index === e && s.fragment.sn === t)
        return s;
    }
  return null;
}
function ws(n) {
  n.forEach((t, e) => {
    var i;
    (i = t.details) == null || i.fragments.forEach((s) => {
      s.level = e, s.initSegment && (s.initSegment.level = e);
    });
  });
}
function En(n, t) {
  return n !== t && t ? Mi(n) !== Mi(t) : !1;
}
function Mi(n) {
  return n.replace(/\?[^?]*$/, "");
}
class vn extends Rt {
  constructor(t, e) {
    super(e, t.logger), this.hls = void 0, this.canLoad = !1, this.timer = -1, this.hls = t;
  }
  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(t, e, i) {
    const s = e?.renditionReports;
    if (s) {
      let r = -1;
      for (let a = 0; a < s.length; a++) {
        const o = s[a];
        let u;
        try {
          u = new self.URL(o.URI, e.url).href;
        } catch (l) {
          this.warn(`Could not construct new URL for Rendition Report: ${l}`), u = o.URI || "";
        }
        if (u === t) {
          r = a;
          break;
        } else u === t.substring(0, u.length) && (r = a);
      }
      if (r !== -1) {
        const a = s[r], o = parseInt(a["LAST-MSN"]) || e.lastPartSn;
        let u = parseInt(a["LAST-PART"]) || e.lastPartIndex;
        if (this.hls.config.lowLatencyMode) {
          const d = Math.min(e.age - e.partTarget, e.targetduration);
          u >= 0 && d > e.partTarget && (u += 1);
        }
        const l = i && mi(i);
        return new pi(o, u >= 0 ? u : void 0, l);
      }
    }
  }
  loadPlaylist(t) {
    this.clearTimer();
  }
  loadingPlaylist(t, e) {
    this.clearTimer();
  }
  shouldLoadPlaylist(t) {
    return this.canLoad && !!t && !!t.url && (!t.details || t.details.live);
  }
  getUrlWithDirectives(t, e) {
    if (e)
      try {
        return e.addDirectives(t);
      } catch (i) {
        this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`);
      }
    return t;
  }
  playlistLoaded(t, e, i) {
    const {
      details: s,
      stats: r
    } = e, a = self.performance.now(), o = r.loading.first ? Math.max(0, a - r.loading.first) : 0;
    s.advancedDateTime = Date.now() - o;
    const u = this.hls.config.timelineOffset;
    if (u !== s.appliedTimelineOffset) {
      const d = Math.max(u || 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 e ? e.levelInfo : e.track;
      if (s.reloaded(i), i && s.fragments.length > 0) {
        cn(i, s, this);
        const T = s.playlistParsingError;
        if (T) {
          this.warn(T);
          const v = this.hls;
          if (!v.config.ignorePlaylistParsingErrors) {
            var l;
            const {
              networkDetails: x
            } = e;
            v.trigger(E.ERROR, {
              type: Y.NETWORK_ERROR,
              details: D.LEVEL_PARSING_ERROR,
              fatal: !1,
              url: s.url,
              error: T,
              reason: T.message,
              level: e.level || void 0,
              parent: (l = s.fragments[0]) == null ? void 0 : l.type,
              networkDetails: x,
              stats: r
            });
            return;
          }
          s.playlistParsingError = null;
        }
      }
      s.requestScheduled === -1 && (s.requestScheduled = r.loading.start);
      const h = this.hls.mainForwardBufferInfo, c = h ? h.end - h.len : 0, f = (s.edge - c) * 1e3, g = Ps(s, f);
      if (s.requestScheduled + g < a ? s.requestScheduled = a : s.requestScheduled += g, this.log(`live playlist ${t} ${s.advanced ? "REFRESHED " + s.lastPartSn + "-" + s.lastPartIndex : s.updated ? "UPDATED" : "MISSED"}`), !this.canLoad || !s.live)
        return;
      let p, m, y;
      if (s.canBlockReload && s.endSN && s.advanced) {
        const T = this.hls.config.lowLatencyMode, v = s.lastPartSn, x = s.endSN, A = s.lastPartIndex, C = A !== -1, S = v === x;
        C ? S ? (m = x + 1, y = T ? 0 : A) : (m = v, y = T ? A + 1 : s.maxPartIndex) : m = x + 1;
        const R = s.age, b = R + s.ageHeader;
        let I = Math.min(b - s.partTarget, s.targetduration * 1.5);
        if (I > 0) {
          if (b > s.targetduration * 3)
            this.log(`Playlist last advanced ${R.toFixed(2)}s ago. Omitting segment and part directives.`), m = void 0, y = void 0;
          else if (i != null && i.tuneInGoal && b - s.partTarget > i.tuneInGoal)
            this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${I} with playlist age: ${s.age}`), I = 0;
          else {
            const _ = Math.floor(I / s.targetduration);
            if (m += _, y !== void 0) {
              const F = Math.round(I % s.targetduration / s.partTarget);
              y += F;
            }
            this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${I} skip sn ${_} to part ${y}`);
          }
          s.tuneInGoal = I;
        }
        if (p = this.getDeliveryDirectives(s, e.deliveryDirectives, m, y), T || !S) {
          s.requestScheduled = a, this.loadingPlaylist(d, p);
          return;
        }
      } else (s.canBlockReload || s.canSkipUntil) && (p = this.getDeliveryDirectives(s, e.deliveryDirectives, m, y));
      p && m !== void 0 && s.canBlockReload && (s.requestScheduled = r.loading.first + Math.max(g - o * 2, g / 2)), this.scheduleLoading(d, p, s);
    } else
      this.clearTimer();
  }
  scheduleLoading(t, e, i) {
    const s = i || t.details;
    if (!s) {
      this.loadingPlaylist(t, e);
      return;
    }
    const r = self.performance.now(), a = s.requestScheduled;
    if (r >= a) {
      this.loadingPlaylist(t, e);
      return;
    }
    const o = a - r;
    this.log(`reload live playlist ${t.name || t.bitrate + "bps"} in ${Math.round(o)} ms`), this.clearTimer(), this.timer = self.setTimeout(() => this.loadingPlaylist(t, e), o);
  }
  getDeliveryDirectives(t, e, i, s) {
    let r = mi(t);
    return e != null && e.skip && t.deltaUpdateFailed && (i = e.msn, s = e.part, r = ue.No), new pi(i, s, r);
  }
  checkRetry(t) {
    const e = t.details, i = ge(t), s = t.errorAction, {
      action: r,
      retryCount: a = 0,
      retryConfig: o
    } = s || {}, u = !!s && !!o && (r === at.RetryRequest || !s.resolved && r === at.SendAlternateToPenaltyBox);
    if (u) {
      var l;
      if (a >= o.maxNumRetry)
        return !1;
      if (i && (l = t.context) != null && l.deliveryDirectives)
        this.warn(`Retrying playlist loading ${a + 1}/${o.maxNumRetry} after "${e}" without delivery-directives`), this.loadPlaylist();
      else {
        const d = Je(o, a);
        this.clearTimer(), this.timer = self.setTimeout(() => this.loadPlaylist(), d), this.warn(`Retrying playlist loading ${a + 1}/${o.maxNumRetry} after "${e}" in ${d}ms`);
      }
      t.levelRetry = !0, s.resolved = !0;
    }
    return u;
  }
}
var lt = {
  NOT_LOADED: "NOT_LOADED",
  APPENDING: "APPENDING",
  PARTIAL: "PARTIAL",
  OK: "OK"
};
class yn {
  constructor(t) {
    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 = t, this._registerListeners();
  }
  _registerListeners() {
    const {
      hls: t
    } = this;
    t && (t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.BUFFER_APPENDED, this.onBufferAppended, this), t.on(E.FRAG_BUFFERED, this.onFragBuffered, this), t.on(E.FRAG_LOADED, this.onFragLoaded, this));
  }
  _unregisterListeners() {
    const {
      hls: t
    } = this;
    t && (t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.BUFFER_APPENDED, this.onBufferAppended, this), t.off(E.FRAG_BUFFERED, this.onFragBuffered, this), t.off(E.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(t, e) {
    const i = this.activePartLists[e];
    if (i)
      for (let s = i.length; s--; ) {
        const r = i[s];
        if (!r)
          break;
        if (r.start <= t && t <= r.end && r.loaded)
          return r;
      }
    return this.getBufferedFrag(t, e);
  }
  /**
   * 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(t, e) {
    return this.getFragAtPos(t, e, !0);
  }
  getFragAtPos(t, e, i) {
    const {
      fragments: s
    } = this, r = Object.keys(s);
    for (let a = r.length; a--; ) {
      const o = s[r[a]];
      if (o?.body.type === e && (!i || o.buffered)) {
        const u = o.body;
        if (u.start <= t && t <= u.end)
          return u;
      }
    }
    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(t, e, i, s, r) {
    this.timeRanges && (this.timeRanges[t] = e);
    const a = s?.fragment.sn || -1;
    Object.keys(this.fragments).forEach((o) => {
      const u = this.fragments[o];
      if (!u || a >= u.body.sn)
        return;
      if (!u.buffered && (!u.loaded || r)) {
        u.body.type === i && this.removeFragment(u.body);
        return;
      }
      const l = u.range[t];
      if (l) {
        if (l.time.length === 0) {
          this.removeFragment(u.body);
          return;
        }
        l.time.some((d) => {
          const h = !this.isTimeBuffered(d.startPTS, d.endPTS, e);
          return h && this.removeFragment(u.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(t) {
    const e = this.timeRanges;
    if (!e || t.frag.sn === "initSegment")
      return;
    const i = t.frag, s = Bt(i), r = this.fragments[s];
    if (!r || r.buffered && i.gap)
      return;
    const a = !i.relurl;
    Object.keys(e).forEach((o) => {
      const u = i.elementaryStreams[o];
      if (!u)
        return;
      const l = e[o], d = a || u.partial === !0;
      r.range[o] = this.getBufferedTimes(i, t.part, d, l);
    }), r.loaded = null, Object.keys(r.range).length ? (r.buffered = !0, (r.body.endList = i.endList || r.body.endList) && (this.endListFragments[r.body.type] = r), ee(r) || this.removeParts(i.sn - 1, i.type)) : this.removeFragment(r.body);
  }
  removeParts(t, e) {
    const i = this.activePartLists[e];
    i && (this.activePartLists[e] = Ni(i, (s) => s.fragment.sn >= t));
  }
  fragBuffered(t, e) {
    const i = Bt(t);
    let s = this.fragments[i];
    !s && e && (s = this.fragments[i] = {
      body: t,
      appendedPTS: null,
      loaded: null,
      buffered: !1,
      range: /* @__PURE__ */ Object.create(null)
    }, t.gap && (this.hasGaps = !0)), s && (s.loaded = null, s.buffered = !0);
  }
  getBufferedTimes(t, e, i, s) {
    const r = {
      time: [],
      partial: i
    }, a = t.start, o = t.end, u = t.minEndPTS || o, l = t.maxStartPTS || a;
    for (let d = 0; d < s.length; d++) {
      const h = s.start(d) - this.bufferPadding, c = s.end(d) + this.bufferPadding;
      if (l >= h && u <= c) {
        r.time.push({
          startPTS: Math.max(a, s.start(d)),
          endPTS: Math.min(o, s.end(d))
        });
        break;
      } else if (a < c && o > h) {
        const f = Math.max(a, s.start(d)), g = Math.min(o, s.end(d));
        g > f && (r.partial = !0, r.time.push({
          startPTS: f,
          endPTS: g
        }));
      } else if (o <= h)
        break;
    }
    return r;
  }
  /**
   * Gets the partial fragment for a certain time
   */
  getPartialFragment(t) {
    let e = null, i, s, r, a = 0;
    const {
      bufferPadding: o,
      fragments: u
    } = this;
    return Object.keys(u).forEach((l) => {
      const d = u[l];
      d && ee(d) && (s = d.body.start - o, r = d.body.end + o, t >= s && t <= r && (i = Math.min(t - s, r - t), a <= i && (e = d.body, a = i)));
    }), e;
  }
  isEndListAppended(t) {
    const e = this.endListFragments[t];
    return e !== void 0 && (e.buffered || ee(e));
  }
  getState(t) {
    const e = Bt(t), i = this.fragments[e];
    return i ? i.buffered ? ee(i) ? lt.PARTIAL : lt.OK : lt.APPENDING : lt.NOT_LOADED;
  }
  isTimeBuffered(t, e, i) {
    let s, r;
    for (let a = 0; a < i.length; a++) {
      if (s = i.start(a) - this.bufferPadding, r = i.end(a) + this.bufferPadding, t >= s && e <= r)
        return !0;
      if (e <= s)
        return !1;
    }
    return !1;
  }
  onManifestLoading() {
    this.removeAllFragments();
  }
  onFragLoaded(t, e) {
    if (e.frag.sn === "initSegment" || e.frag.bitrateTest)
      return;
    const i = e.frag, s = e.part ? null : e, r = Bt(i);
    this.fragments[r] = {
      body: i,
      appendedPTS: null,
      loaded: s,
      buffered: !1,
      range: /* @__PURE__ */ Object.create(null)
    };
  }
  onBufferAppended(t, e) {
    const {
      frag: i,
      part: s,
      timeRanges: r,
      type: a
    } = e;
    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 = r;
    const u = r[a];
    this.detectEvictedFragments(a, u, o, s);
  }
  onFragBuffered(t, e) {
    this.detectPartialFragments(e);
  }
  hasFragment(t) {
    const e = Bt(t);
    return !!this.fragments[e];
  }
  hasFragments(t) {
    const {
      fragments: e
    } = this, i = Object.keys(e);
    if (!t)
      return i.length > 0;
    for (let s = i.length; s--; ) {
      const r = e[i[s]];
      if (r?.body.type === t)
        return !0;
    }
    return !1;
  }
  hasParts(t) {
    var e;
    return !!((e = this.activePartLists[t]) != null && e.length);
  }
  removeFragmentsInRange(t, e, i, s, r) {
    s && !this.hasGaps || Object.keys(this.fragments).forEach((a) => {
      const o = this.fragments[a];
      if (!o)
        return;
      const u = o.body;
      u.type !== i || s && !u.gap || u.start < e && u.end > t && (o.buffered || r) && this.removeFragment(u);
    });
  }
  removeFragment(t) {
    const e = Bt(t);
    t.clearElementaryStreamInfo();
    const i = this.activePartLists[t.type];
    if (i) {
      const s = t.sn;
      this.activePartLists[t.type] = Ni(i, (r) => r.fragment.sn !== s);
    }
    delete this.fragments[e], t.endList && delete this.endListFragments[t.type];
  }
  removeAllFragments() {
    var t;
    this.fragments = /* @__PURE__ */ Object.create(null), this.endListFragments = /* @__PURE__ */ Object.create(null), this.activePartLists = /* @__PURE__ */ Object.create(null), this.hasGaps = !1;
    const e = (t = this.hls) == null || (t = t.latestLevelDetails) == null ? void 0 : t.partList;
    e && e.forEach((i) => i.clearElementaryStreamInfo());
  }
}
function ee(n) {
  var t, e, i;
  return n.buffered && !!(n.body.gap || (t = n.range.video) != null && t.partial || (e = n.range.audio) != null && e.partial || (i = n.range.audiovideo) != null && i.partial);
}
function Bt(n) {
  return `${n.type}_${n.level}_${n.sn}`;
}
function Ni(n, t) {
  return n.filter((e) => {
    const i = t(e);
    return i || e.clearElementaryStreamInfo(), i;
  });
}
class Tn {
  constructor(t, e, i) {
    this.subtle = void 0, this.aesIV = void 0, this.aesMode = void 0, this.subtle = t, this.aesIV = e, this.aesMode = i;
  }
  decrypt(t, e) {
    switch (this.aesMode) {
      case Pt.cbc:
        return this.subtle.decrypt({
          name: "AES-CBC",
          iv: this.aesIV
        }, e, t);
      case Pt.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
          e,
          t
        );
      default:
        throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
    }
  }
}
function xn(n) {
  const t = n.byteLength, e = t && new DataView(n.buffer).getUint8(t - 1);
  return e ? n.slice(0, t - e) : n;
}
class Sn {
  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_(t) {
    const e = new DataView(t), i = new Uint32Array(4);
    for (let s = 0; s < 4; s++)
      i[s] = e.getUint32(s * 4);
    return i;
  }
  initTable() {
    const t = this.sBox, e = this.invSBox, i = this.subMix, s = i[0], r = i[1], a = i[2], o = i[3], u = this.invSubMix, l = u[0], d = u[1], h = u[2], c = u[3], f = new Uint32Array(256);
    let g = 0, p = 0, m = 0;
    for (m = 0; m < 256; m++)
      m < 128 ? f[m] = m << 1 : f[m] = m << 1 ^ 283;
    for (m = 0; m < 256; m++) {
      let y = p ^ p << 1 ^ p << 2 ^ p << 3 ^ p << 4;
      y = y >>> 8 ^ y & 255 ^ 99, t[g] = y, e[y] = g;
      const T = f[g], v = f[T], x = f[v];
      let A = f[y] * 257 ^ y * 16843008;
      s[g] = A << 24 | A >>> 8, r[g] = A << 16 | A >>> 16, a[g] = A << 8 | A >>> 24, o[g] = A, A = x * 16843009 ^ v * 65537 ^ T * 257 ^ g * 16843008, l[y] = A << 24 | A >>> 8, d[y] = A << 16 | A >>> 16, h[y] = A << 8 | A >>> 24, c[y] = A, g ? (g = T ^ f[f[f[x ^ T]]], p ^= f[f[p]]) : g = p = 1;
    }
  }
  expandKey(t) {
    const e = this.uint8ArrayToUint32Array_(t);
    let i = !0, s = 0;
    for (; s < e.length && i; )
      i = e[s] === this.key[s], s++;
    if (i)
      return;
    this.key = e;
    const r = this.keySize = e.length;
    if (r !== 4 && r !== 6 && r !== 8)
      throw new Error("Invalid aes key size=" + r);
    const a = this.ksRows = (r + 6 + 1) * 4;
    let o, u;
    const l = this.keySchedule = new Uint32Array(a), d = this.invKeySchedule = new Uint32Array(a), h = this.sBox, c = this.rcon, f = this.invSubMix, g = f[0], p = f[1], m = f[2], y = f[3];
    let T, v;
    for (o = 0; o < a; o++) {
      if (o < r) {
        T = l[o] = e[o];
        continue;
      }
      v = T, o % r === 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 ^= c[o / r | 0] << 24) : r > 6 && o % r === 4 && (v = h[v >>> 24] << 24 | h[v >>> 16 & 255] << 16 | h[v >>> 8 & 255] << 8 | h[v & 255]), l[o] = T = (l[o - r] ^ v) >>> 0;
    }
    for (u = 0; u < a; u++)
      o = a - u, u & 3 ? v = l[o] : v = l[o - 4], u < 4 || o <= 4 ? d[u] = v : d[u] = g[h[v >>> 24]] ^ p[h[v >>> 16 & 255]] ^ m[h[v >>> 8 & 255]] ^ y[h[v & 255]], d[u] = d[u] >>> 0;
  }
  // Adding this as a method greatly improves performance.
  networkToHostOrderSwap(t) {
    return t << 24 | (t & 65280) << 8 | (t & 16711680) >> 8 | t >>> 24;
  }
  decrypt(t, e, i) {
    const s = this.keySize + 6, r = this.invKeySchedule, a = this.invSBox, o = this.invSubMix, u = o[0], l = o[1], d = o[2], h = o[3], c = this.uint8ArrayToUint32Array_(i);
    let f = c[0], g = c[1], p = c[2], m = c[3];
    const y = new Int32Array(t), T = new Int32Array(y.length);
    let v, x, A, C, S, R, b, I, _, F, $, V, N, P;
    const G = this.networkToHostOrderSwap;
    for (; e < y.length; ) {
      for (_ = G(y[e]), F = G(y[e + 1]), $ = G(y[e + 2]), V = G(y[e + 3]), S = _ ^ r[0], R = V ^ r[1], b = $ ^ r[2], I = F ^ r[3], N = 4, P = 1; P < s; P++)
        v = u[S >>> 24] ^ l[R >> 16 & 255] ^ d[b >> 8 & 255] ^ h[I & 255] ^ r[N], x = u[R >>> 24] ^ l[b >> 16 & 255] ^ d[I >> 8 & 255] ^ h[S & 255] ^ r[N + 1], A = u[b >>> 24] ^ l[I >> 16 & 255] ^ d[S >> 8 & 255] ^ h[R & 255] ^ r[N + 2], C = u[I >>> 24] ^ l[S >> 16 & 255] ^ d[R >> 8 & 255] ^ h[b & 255] ^ r[N + 3], S = v, R = x, b = A, I = C, N = N + 4;
      v = a[S >>> 24] << 24 ^ a[R >> 16 & 255] << 16 ^ a[b >> 8 & 255] << 8 ^ a[I & 255] ^ r[N], x = a[R >>> 24] << 24 ^ a[b >> 16 & 255] << 16 ^ a[I >> 8 & 255] << 8 ^ a[S & 255] ^ r[N + 1], A = a[b >>> 24] << 24 ^ a[I >> 16 & 255] << 16 ^ a[S >> 8 & 255] << 8 ^ a[R & 255] ^ r[N + 2], C = a[I >>> 24] << 24 ^ a[S >> 16 & 255] << 16 ^ a[R >> 8 & 255] << 8 ^ a[b & 255] ^ r[N + 3], T[e] = G(v ^ f), T[e + 1] = G(C ^ g), T[e + 2] = G(A ^ p), T[e + 3] = G(x ^ m), f = _, g = F, p = $, m = V, e = e + 4;
    }
    return T.buffer;
  }
}
class Ln {
  constructor(t, e, i) {
    this.subtle = void 0, this.key = void 0, this.aesMode = void 0, this.subtle = t, this.key = e, this.aesMode = i;
  }
  expandKey() {
    const t = An(this.aesMode);
    return this.subtle.importKey("raw", this.key, {
      name: t
    }, !1, ["encrypt", "decrypt"]);
  }
}
function An(n) {
  switch (n) {
    case Pt.cbc:
      return "AES-CBC";
    case Pt.ctr:
      return "AES-CTR";
    default:
      throw new Error(`[FastAESKey] invalid aes mode ${n}`);
  }
}
const Rn = 16;
class ti {
  constructor(t, {
    removePKCS7Padding: e = !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 = t.enableSoftwareAES, this.removePKCS7Padding = e, e)
      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: t,
      remainderData: e
    } = this;
    if (!t || e)
      return this.reset(), null;
    const i = new Uint8Array(t);
    return this.reset(), this.removePKCS7Padding ? xn(i) : i;
  }
  reset() {
    this.currentResult = null, this.currentIV = null, this.remainderData = null, this.softwareDecrypter && (this.softwareDecrypter = null);
  }
  decrypt(t, e, i, s) {
    return this.useSoftware ? new Promise((r, a) => {
      const o = ArrayBuffer.isView(t) ? t : new Uint8Array(t);
      this.softwareDecrypt(o, e, i, s);
      const u = this.flush();
      u ? r(u.buffer) : a(new Error("[softwareDecrypt] Failed to decrypt data"));
    }) : this.webCryptoDecrypt(new Uint8Array(t), e, 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(t, e, i, s) {
    const {
      currentIV: r,
      currentResult: a,
      remainderData: o
    } = this;
    if (s !== Pt.cbc || e.byteLength !== 16)
      return J.warn("SoftwareDecrypt: can only handle AES-128-CBC"), null;
    this.logOnce("JS AES decrypt"), o && (t = mt(o, t), this.remainderData = null);
    const u = this.getValidChunk(t);
    if (!u.length)
      return null;
    r && (i = r);
    let l = this.softwareDecrypter;
    l || (l = this.softwareDecrypter = new Sn()), l.expandKey(e);
    const d = a;
    return this.currentResult = l.decrypt(u.buffer, 0, i), this.currentIV = u.slice(-16).buffer, d || null;
  }
  webCryptoDecrypt(t, e, i, s) {
    if (this.key !== e || !this.fastAesKey) {
      if (!this.subtle)
        return Promise.resolve(this.onWebCryptoError(t, e, i, s));
      this.key = e, this.fastAesKey = new Ln(this.subtle, e, s);
    }
    return this.fastAesKey.expandKey().then((r) => this.subtle ? (this.logOnce("WebCrypto AES decrypt"), new Tn(this.subtle, new Uint8Array(i), s).decrypt(t.buffer, r)) : Promise.reject(new Error("web crypto not initialized"))).catch((r) => (J.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`), this.onWebCryptoError(t, e, i, s)));
  }
  onWebCryptoError(t, e, i, s) {
    const r = this.enableSoftwareAES;
    if (r) {
      this.useSoftware = !0, this.logEnabled = !0, this.softwareDecrypt(t, e, i, s);
      const a = this.flush();
      if (a)
        return a.buffer;
    }
    throw new Error("WebCrypto" + (r ? " and softwareDecrypt" : "") + ": failed to decrypt data");
  }
  getValidChunk(t) {
    let e = t;
    const i = t.length - t.length % Rn;
    return i !== t.length && (e = t.slice(0, i), this.remainderData = t.slice(i)), e;
  }
  logOnce(t) {
    this.logEnabled && (J.log(`[decrypter]: ${t}`), this.logEnabled = !1);
  }
}
const Bi = Math.pow(2, 17);
class bn {
  constructor(t) {
    this.config = void 0, this.loader = null, this.partLoadTimeout = -1, this.config = t;
  }
  destroy() {
    this.loader && (this.loader.destroy(), this.loader = null);
  }
  abort() {
    this.loader && this.loader.abort();
  }
  load(t, e) {
    const i = t.url;
    if (!i)
      return Promise.reject(new Lt({
        type: Y.NETWORK_ERROR,
        details: D.FRAG_LOAD_ERROR,
        fatal: !1,
        frag: t,
        error: new Error(`Fragment does not have a ${i ? "part list" : "url"}`),
        networkDetails: null
      }));
    this.abort();
    const s = this.config, r = s.fLoader, a = s.loader;
    return new Promise((o, u) => {
      if (this.loader && this.loader.destroy(), t.gap)
        if (t.tagList.some((g) => g[0] === "GAP")) {
          u(Ui(t));
          return;
        } else
          t.gap = !1;
      const l = this.loader = r ? new r(s) : new a(s), d = $i(t);
      t.loader = l;
      const h = xi(s.fragLoadPolicy.default), c = {
        loadPolicy: h,
        timeout: h.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: t.sn === "initSegment" ? 1 / 0 : Bi
      };
      t.stats = l.stats;
      const f = {
        onSuccess: (g, p, m, y) => {
          this.resetLoader(t, l);
          let T = g.data;
          m.resetIV && t.decryptdata && (t.decryptdata.iv = new Uint8Array(T.slice(0, 16)), T = T.slice(16)), o({
            frag: t,
            part: null,
            payload: T,
            networkDetails: y
          });
        },
        onError: (g, p, m, y) => {
          this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.FRAG_LOAD_ERROR,
            fatal: !1,
            frag: t,
            response: ct({
              url: i,
              data: void 0
            }, g),
            error: new Error(`HTTP Error ${g.code} ${g.text}`),
            networkDetails: m,
            stats: y
          }));
        },
        onAbort: (g, p, m) => {
          this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.INTERNAL_ABORTED,
            fatal: !1,
            frag: t,
            error: new Error("Aborted"),
            networkDetails: m,
            stats: g
          }));
        },
        onTimeout: (g, p, m) => {
          this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.FRAG_LOAD_TIMEOUT,
            fatal: !1,
            frag: t,
            error: new Error(`Timeout after ${c.timeout}ms`),
            networkDetails: m,
            stats: g
          }));
        }
      };
      e && (f.onProgress = (g, p, m, y) => e({
        frag: t,
        part: null,
        payload: m,
        networkDetails: y
      })), l.load(d, c, f);
    });
  }
  loadPart(t, e, i) {
    this.abort();
    const s = this.config, r = s.fLoader, a = s.loader;
    return new Promise((o, u) => {
      if (this.loader && this.loader.destroy(), t.gap || e.gap) {
        u(Ui(t, e));
        return;
      }
      const l = this.loader = r ? new r(s) : new a(s), d = $i(t, e);
      t.loader = l;
      const h = xi(s.fragLoadPolicy.default), c = {
        loadPolicy: h,
        timeout: h.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0,
        highWaterMark: Bi
      };
      e.stats = l.stats, l.load(d, c, {
        onSuccess: (f, g, p, m) => {
          this.resetLoader(t, l), this.updateStatsFromPart(t, e);
          const y = {
            frag: t,
            part: e,
            payload: f.data,
            networkDetails: m
          };
          i(y), o(y);
        },
        onError: (f, g, p, m) => {
          this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.FRAG_LOAD_ERROR,
            fatal: !1,
            frag: t,
            part: e,
            response: ct({
              url: d.url,
              data: void 0
            }, f),
            error: new Error(`HTTP Error ${f.code} ${f.text}`),
            networkDetails: p,
            stats: m
          }));
        },
        onAbort: (f, g, p) => {
          t.stats.aborted = e.stats.aborted, this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.INTERNAL_ABORTED,
            fatal: !1,
            frag: t,
            part: e,
            error: new Error("Aborted"),
            networkDetails: p,
            stats: f
          }));
        },
        onTimeout: (f, g, p) => {
          this.resetLoader(t, l), u(new Lt({
            type: Y.NETWORK_ERROR,
            details: D.FRAG_LOAD_TIMEOUT,
            fatal: !1,
            frag: t,
            part: e,
            error: new Error(`Timeout after ${c.timeout}ms`),
            networkDetails: p,
            stats: f
          }));
        }
      });
    });
  }
  updateStatsFromPart(t, e) {
    const i = t.stats, s = e.stats, r = s.total;
    if (i.loaded += s.loaded, r) {
      const u = Math.round(t.duration / e.duration), l = Math.min(Math.round(i.loaded / r), u), h = (u - 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(t, e) {
    t.loader = null, this.loader === e && (self.clearTimeout(this.partLoadTimeout), this.loader = null), e.destroy();
  }
}
function $i(n, t = null) {
  const e = t || n, i = {
    frag: n,
    part: t,
    responseType: "arraybuffer",
    url: e.url,
    headers: {},
    rangeStart: 0,
    rangeEnd: 0
  }, s = e.byteRangeStartOffset, r = e.byteRangeEndOffset;
  if (B(s) && B(r)) {
    var a;
    let o = s, u = r;
    if (n.sn === "initSegment" && In((a = n.decryptdata) == null ? void 0 : a.method)) {
      const l = r - s;
      l % 16 && (u = r + (16 - l % 16)), s !== 0 && (i.resetIV = !0, o = s - 16);
    }
    i.rangeStart = o, i.rangeEnd = u;
  }
  return i;
}
function Ui(n, t) {
  const e = new Error(`GAP ${n.gap ? "tag" : "attribute"} found`), i = {
    type: Y.MEDIA_ERROR,
    details: D.FRAG_GAP,
    fatal: !1,
    frag: n,
    error: e,
    networkDetails: null
  };
  return t && (i.part = t), (t || n).stats.aborted = !0, new Lt(i);
}
function In(n) {
  return n === "AES-128" || n === "AES-256";
}
class Lt extends Error {
  constructor(t) {
    super(t.error.message), this.data = void 0, this.data = t;
  }
}
class Fs extends Rt {
  constructor(t, e) {
    super(t, e), 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(t) {
    return this._tickInterval ? !1 : (this._tickCallCount = 0, this._tickInterval = self.setInterval(this._boundTick, t), !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 Ms {
  constructor(t, e, i, s = 0, r = -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 = ie(), this.buffering = {
      audio: ie(),
      video: ie(),
      audiovideo: ie()
    }, this.level = t, this.sn = e, this.id = i, this.size = s, this.part = r, this.partial = a;
  }
}
function ie() {
  return {
    start: 0,
    executeStart: 0,
    executeEnd: 0,
    end: 0
  };
}
const Gi = {
  length: 0,
  start: () => 0,
  end: () => 0
};
class q {
  /**
   * Return true if `media`'s buffered include `position`
   */
  static isBuffered(t, e) {
    if (t) {
      const i = q.getBuffered(t);
      for (let s = i.length; s--; )
        if (e >= i.start(s) && e <= i.end(s))
          return !0;
    }
    return !1;
  }
  static bufferedRanges(t) {
    if (t) {
      const e = q.getBuffered(t);
      return q.timeRangesToArray(e);
    }
    return [];
  }
  static timeRangesToArray(t) {
    const e = [];
    for (let i = 0; i < t.length; i++)
      e.push({
        start: t.start(i),
        end: t.end(i)
      });
    return e;
  }
  static bufferInfo(t, e, i) {
    if (t) {
      const s = q.bufferedRanges(t);
      if (s.length)
        return q.bufferedInfo(s, e, i);
    }
    return {
      len: 0,
      start: e,
      end: e,
      bufferedIndex: -1
    };
  }
  static bufferedInfo(t, e, i) {
    e = Math.max(0, e), t.length > 1 && t.sort((d, h) => d.start - h.start || h.end - d.end);
    let s = -1, r = [];
    if (i)
      for (let d = 0; d < t.length; d++) {
        e >= t[d].start && e <= t[d].end && (s = d);
        const h = r.length;
        if (h) {
          const c = r[h - 1].end;
          t[d].start - c < i ? t[d].end > c && (r[h - 1].end = t[d].end) : r.push(t[d]);
        } else
          r.push(t[d]);
      }
    else
      r = t;
    let a = 0, o, u = e, l = e;
    for (let d = 0; d < r.length; d++) {
      const h = r[d].start, c = r[d].end;
      if (s === -1 && e >= h && e <= c && (s = d), e + i >= h && e < c)
        u = h, l = c, a = l - e;
      else if (e + i < h) {
        o = h;
        break;
      }
    }
    return {
      len: a,
      start: u || 0,
      end: l || 0,
      nextStart: o,
      buffered: t,
      bufferedIndex: s
    };
  }
  /**
   * Safe method to get buffered property.
   * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
   */
  static getBuffered(t) {
    try {
      return t.buffered || Gi;
    } catch (e) {
      return J.log("failed to get media.buffered", e), Gi;
    }
  }
}
function jt(n, t) {
  for (let i = 0, s = n.length; i < s; i++) {
    var e;
    if (((e = n[i]) == null ? void 0 : e.cc) === t)
      return n[i];
  }
  return null;
}
function Dn(n, t) {
  return !!(n && t.startCC < n.endCC && t.endCC > n.startCC);
}
function Vi(n, t) {
  const e = n.start + t;
  n.startPTS = e, n.setStart(e), n.endPTS = e + n.duration;
}
function Ns(n, t) {
  const e = t.fragments;
  for (let i = 0, s = e.length; i < s; i++)
    Vi(e[i], n);
  t.fragmentHint && Vi(t.fragmentHint, n), t.alignedSliding = !0;
}
function Cn(n, t) {
  n && (_n(t, n), t.alignedSliding || Pn(t, n), !t.alignedSliding && !t.skippedSegments && _s(n, t, !1));
}
function _n(n, t) {
  if (!Dn(t, n))
    return;
  const e = Math.min(t.endCC, n.endCC), i = jt(t.fragments, e), s = jt(n.fragments, e);
  if (!i || !s)
    return;
  J.log(`Aligning playlist at start of dicontinuity sequence ${e}`);
  const r = i.start - s.start;
  Ns(r, n);
}
function Pn(n, t) {
  if (!n.hasProgramDateTime || !t.hasProgramDateTime)
    return;
  const e = n.fragments, i = t.fragments;
  if (!e.length || !i.length)
    return;
  let s, r;
  const a = Math.min(t.endCC, n.endCC);
  t.startCC < a && n.startCC < a && (s = jt(i, a), r = jt(e, a)), (!s || !r) && (s = i[Math.floor(i.length / 2)], r = jt(e, s.cc) || e[Math.floor(e.length / 2)]);
  const o = s.programDateTime, u = r.programDateTime;
  if (!o || !u)
    return;
  const l = (u - o) / 1e3 - (r.start - s.start);
  Ns(l, n);
}
function wt(n, t, e) {
  Ct(n, t, e), n.addEventListener(t, e);
}
function Ct(n, t, e) {
  n.removeEventListener(t, e);
}
const kn = {
  toString: function(n) {
    let t = "";
    const e = n.length;
    for (let i = 0; i < e; i++)
      t += `[${n.start(i).toFixed(3)}-${n.end(i).toFixed(3)}]`;
    return t;
  }
}, k = {
  STOPPED: "STOPPED",
  IDLE: "IDLE",
  KEY_LOADING: "KEY_LOADING",
  FRAG_LOADING: "FRAG_LOADING",
  FRAG_LOADING_WAITING_RETRY: "FRAG_LOADING_WAITING_RETRY",
  PARSING: "PARSING",
  PARSED: "PARSED",
  ENDED: "ENDED",
  ERROR: "ERROR",
  WAITING_LEVEL: "WAITING_LEVEL"
};
class On extends Fs {
  constructor(t, e, i, s, r) {
    super(s, t.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: u,
        mediaBuffer: l,
        state: d
      } = this, h = u ? u.currentTime : 0, c = q.bufferInfo(l || u, h, a.maxBufferHole), f = !c.len;
      if (this.log(`Media seeking to ${B(h) ? h.toFixed(3) : h}, state: ${d}, ${f ? "out of" : "in"} buffer`), this.state === k.ENDED)
        this.resetLoadingState();
      else if (o) {
        const g = a.maxFragLookUpTolerance, p = o.start - g, m = o.start + o.duration + g;
        if (f || m < c.start || p > c.end) {
          const y = h > m;
          (h < p || y) && (y && o.loader && (this.log(`Cancelling fragment load for seek (sn: ${o.sn})`), o.abortRequests(), this.resetLoadingState()), this.fragPrevious = null);
        }
      }
      if (u) {
        this.fragmentTracker.removeFragmentsInRange(h, 1 / 0, this.playlistType, !0);
        const g = this.lastCurrentTime;
        if (h > g && (this.lastCurrentTime = h), !this.loadingParts) {
          const p = Math.max(c.end, h), m = this.shouldLoadParts(this.getLevelDetails(), p);
          m && (this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${p.toFixed(2)}`), this.loadingParts = m);
        }
      }
      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 = r, this.hls = t, this.fragmentLoader = new bn(t.config), this.keyLoader = i, this.fragmentTracker = e, this.config = t.config, this.decrypter = new ti(t.config);
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.on(E.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.off(E.ERROR, this.onError, this);
  }
  doTick() {
    this.onTickEnd();
  }
  onTickEnd() {
  }
  startLoad(t) {
  }
  stopLoad() {
    if (this.state === k.STOPPED)
      return;
    this.fragmentLoader.abort(), this.keyLoader.abort(this.playlistType);
    const t = this.fragCurrent;
    t != null && t.loader && (t.abortRequests(), this.fragmentTracker.removeFragment(t)), this.resetTransmuxer(), this.fragCurrent = null, this.fragPrevious = null, this.clearInterval(), this.clearNextTick(), this.state = k.STOPPED;
  }
  get startPositionValue() {
    const {
      nextLoadPosition: t,
      startPosition: e
    } = this;
    return e === -1 && t ? t : e;
  }
  get bufferingEnabled() {
    return this.buffering;
  }
  pauseBuffering() {
    this.buffering = !1;
  }
  resumeBuffering() {
    this.buffering = !0;
  }
  get inFlightFrag() {
    return {
      frag: this.fragCurrent,
      state: this.state
    };
  }
  _streamEnded(t, e) {
    if (e.live || !this.media)
      return !1;
    const i = t.end || 0, s = this.config.timelineOffset || 0;
    if (i <= s)
      return !1;
    const r = t.buffered;
    this.config.maxBufferHole && r && r.length > 1 && (t = q.bufferedInfo(r, t.start, 0));
    const a = t.nextStart;
    if (a && a > s && a < e.edge || this.media.currentTime < t.start)
      return !1;
    const u = e.partList;
    if (u != null && u.length) {
      const d = u[u.length - 1];
      return q.isBuffered(this.media, d.start + d.duration / 2);
    }
    const l = e.fragments[e.fragments.length - 1].type;
    return this.fragmentTracker.isEndListAppended(l);
  }
  getLevelDetails() {
    if (this.levels && this.levelLastLoaded !== null)
      return this.levelLastLoaded.details;
  }
  get timelineOffset() {
    const t = this.config.timelineOffset;
    if (t) {
      var e;
      return ((e = this.getLevelDetails()) == null ? void 0 : e.appliedTimelineOffset) || t;
    }
    return 0;
  }
  onMediaAttached(t, e) {
    const i = this.media = this.mediaBuffer = e.media;
    wt(i, "seeking", this.onMediaSeeking), wt(i, "ended", this.onMediaEnded);
    const s = this.config;
    this.levels && s.autoStartLoad && this.state === k.STOPPED && this.startLoad(s.startPosition);
  }
  onMediaDetaching(t, e) {
    const i = !!e.transferMedia, s = this.media;
    if (s !== null) {
      if (s.ended && (this.log("MSE detaching and video ended, reset startPosition"), this.startPosition = this.lastCurrentTime = 0), Ct(s, "seeking", this.onMediaSeeking), Ct(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(t, e) {
  }
  onManifestLoaded(t, e) {
    this.startTimeOffset = e.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(t, e, i) {
    this.startFragRequested = !0, this._loadFragForPlayback(t, e, i);
  }
  _loadFragForPlayback(t, e, i) {
    const s = (r) => {
      const a = r.frag;
      if (this.fragContextChanged(a)) {
        this.warn(`${a.type} sn: ${a.sn}${r.part ? " part: " + r.part.index : ""} of ${this.fragInfo(a, !1, r.part)}) was dropped during download.`), this.fragmentTracker.removeFragment(a);
        return;
      }
      a.stats.chunkCount++, this._handleFragmentLoadProgress(r);
    };
    this._doFragLoad(t, e, i, s).then((r) => {
      if (!r)
        return;
      const a = this.state, o = r.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 r && (this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`), this.hls.trigger(E.FRAG_LOADED, r)), this._handleFragmentLoadComplete(r);
    }).catch((r) => {
      this.state === k.STOPPED || this.state === k.ERROR || (this.warn(`Frag error: ${r?.message || r}`), this.resetFragmentLoading(t));
    });
  }
  clearTrackerIfNeeded(t) {
    var e;
    const {
      fragmentTracker: i
    } = this;
    if (i.getState(t) === lt.APPENDING) {
      const r = t.type, a = this.getFwdBufferInfo(this.mediaBuffer, r), o = Math.max(t.duration, a ? a.len : this.config.maxBufferLength), u = this.backtrackFragment;
      ((u ? t.sn - u.sn : 0) === 1 || this.reduceMaxBufferLength(o, t.duration)) && i.removeFragment(t);
    } else ((e = this.mediaBuffer) == null ? void 0 : e.buffered.length) === 0 ? i.removeAllFragments() : i.hasParts(t.type) && (i.detectPartialFragments({
      frag: t,
      part: null,
      stats: t.stats,
      id: t.type
    }), i.getState(t) === lt.PARTIAL && i.removeFragment(t));
  }
  checkLiveUpdate(t) {
    if (t.updated && !t.live) {
      const e = t.fragments[t.fragments.length - 1];
      this.fragmentTracker.detectPartialFragments({
        frag: e,
        part: null,
        stats: e.stats,
        id: e.type
      });
    }
    t.fragments[0] || (t.deltaUpdateFailed = !0);
  }
  waitForLive(t) {
    const e = t.details;
    return e?.live && e.type !== "EVENT" && (this.levelLastLoaded !== t || e.expired);
  }
  flushMainBuffer(t, e, i = null) {
    if (!(t - e))
      return;
    const s = {
      startOffset: t,
      endOffset: e,
      type: i
    };
    this.hls.trigger(E.BUFFER_FLUSHING, s);
  }
  _loadInitSegment(t, e) {
    this._doFragLoad(t, e).then((i) => {
      const s = i?.frag;
      if (!s || this.fragContextChanged(s) || !this.levels)
        throw new Error("init load aborted");
      return i;
    }).then((i) => {
      const {
        hls: s
      } = this, {
        frag: r,
        payload: a
      } = i, o = r.decryptdata;
      if (a && a.byteLength > 0 && o != null && o.key && o.iv && Yt(o.method)) {
        const u = self.performance.now();
        return this.decrypter.decrypt(new Uint8Array(a), o.key.buffer, o.iv.buffer, Is(o.method)).catch((l) => {
          throw s.trigger(E.ERROR, {
            type: Y.MEDIA_ERROR,
            details: D.FRAG_DECRYPT_ERROR,
            fatal: !1,
            error: l,
            reason: l.message,
            frag: r
          }), l;
        }).then((l) => {
          const d = self.performance.now();
          return s.trigger(E.FRAG_DECRYPTED, {
            frag: r,
            payload: l,
            stats: {
              tstart: u,
              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(t));
    });
  }
  completeInitSegmentLoad(t) {
    const {
      levels: e
    } = this;
    if (!e)
      throw new Error("init load aborted, missing levels");
    const i = t.frag.stats;
    this.state !== k.STOPPED && (this.state = k.IDLE), t.frag.data = new Uint8Array(t.payload), i.parsing.start = i.buffering.start = self.performance.now(), i.parsing.end = i.buffering.end = self.performance.now(), this.tick();
  }
  unhandledEncryptionError(t, e) {
    var i, s;
    const r = t.tracks;
    if (r && !e.encrypted && ((i = r.audio) != null && i.encrypted || (s = r.video) != null && s.encrypted) && (!this.config.emeEnabled || !this.keyLoader.emeController)) {
      const a = this.media, o = new Error("EME not supported (light build)");
      return this.warn(o.message), !a || a.mediaKeys ? !1 : (this.hls.trigger(E.ERROR, {
        type: Y.KEY_SYSTEM_ERROR,
        details: D.KEY_SYSTEM_NO_KEYS,
        fatal: !0,
        error: o,
        frag: e
      }), this.resetTransmuxer(), !0);
    }
    return !1;
  }
  fragContextChanged(t) {
    const {
      fragCurrent: e
    } = this;
    return !t || !e || t.sn !== e.sn || t.level !== e.level;
  }
  fragBufferedComplete(t, e) {
    const i = this.mediaBuffer ? this.mediaBuffer : this.media;
    if (this.log(`Buffered ${t.type} sn: ${t.sn}${e ? " part: " + e.index : ""} of ${this.fragInfo(t, !1, e)} > buffer:${i ? kn.toString(q.getBuffered(i)) : "(detached)"})`), ft(t)) {
      var s;
      if (t.type !== W.SUBTITLE) {
        const a = t.elementaryStreams;
        if (!Object.keys(a).some((o) => !!a[o])) {
          this.state = k.IDLE;
          return;
        }
      }
      const r = (s = this.levels) == null ? void 0 : s[t.level];
      r != null && r.fragmentError && (this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`), r.fragmentError = 0);
    }
    this.state = k.IDLE;
  }
  _handleFragmentLoadComplete(t) {
    const {
      transmuxer: e
    } = this;
    if (!e)
      return;
    const {
      frag: i,
      part: s,
      partsLoaded: r
    } = t, a = !r || r.length === 0 || r.some((u) => !u), o = new Ms(i.level, i.sn, i.stats.chunkCount + 1, 0, s ? s.index : -1, !a);
    e.flush(o);
  }
  _handleFragmentLoadProgress(t) {
  }
  _doFragLoad(t, e, i = null, s) {
    var r;
    this.fragCurrent = t;
    const a = e.details;
    if (!this.levels || !a)
      throw new Error(`frag load aborted, missing level${a ? "" : " detail"}s`);
    let o = null;
    if (t.encrypted && !((r = t.decryptdata) != null && r.key)) {
      if (this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${t.level}`), this.state = k.KEY_LOADING, this.fragCurrent = t, o = this.keyLoader.load(t).then((c) => {
        if (!this.fragContextChanged(c.frag))
          return this.hls.trigger(E.KEY_LOADED, c), this.state === k.KEY_LOADING && (this.state = k.IDLE), c;
      }), this.hls.trigger(E.KEY_LOADING, {
        frag: t
      }), this.fragCurrent === null)
        return this.log("context changed in KEY_LOADING"), Promise.resolve(null);
    } else t.encrypted || (o = this.keyLoader.loadClear(t, a.encryptedFragments, this.startFragRequested), o && this.log("[eme] blocking frag load until media-keys acquired"));
    const u = this.fragPrevious;
    if (ft(t) && (!u || t.sn !== u.sn)) {
      const c = this.shouldLoadParts(e.details, t.end);
      c !== this.loadingParts && (this.log(`LL-Part loading ${c ? "ON" : "OFF"} loading sn ${u?.sn}->${t.sn}`), this.loadingParts = c);
    }
    if (i = Math.max(t.start, i || 0), this.loadingParts && ft(t)) {
      const c = a.partList;
      if (c && s) {
        i > a.fragmentEnd && a.fragmentHint && (t = a.fragmentHint);
        const f = this.getNextPart(c, t, i);
        if (f > -1) {
          const g = c[f];
          t = this.fragCurrent = g.fragment, this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${c.length - 1}) of ${this.fragInfo(t, !1, g)}) cc: ${t.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`), this.nextLoadPosition = g.start + g.duration, this.state = k.FRAG_LOADING;
          let p;
          return o ? p = o.then((m) => !m || this.fragContextChanged(m.frag) ? null : this.doFragPartsLoad(t, g, e, s)).catch((m) => this.handleFragLoadError(m)) : p = this.doFragPartsLoad(t, g, e, s).catch((m) => this.handleFragLoadError(m)), this.hls.trigger(E.FRAG_LOADING, {
            frag: t,
            part: g,
            targetBufferTime: i
          }), this.fragCurrent === null ? Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")) : p;
        } else if (!t.url || this.loadedEndOfParts(c, i))
          return Promise.resolve(null);
      }
    }
    if (ft(t) && this.loadingParts) {
      var l;
      this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(l = a.partList) == null ? void 0 : l.filter((c) => c.loaded).map((c) => `[${c.start}-${c.end}]`)}`), this.loadingParts = !1;
    } else if (!t.url)
      return Promise.resolve(null);
    this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t, !1)}) cc: ${t.cc} ${"[" + a.startSN + "-" + a.endSN + "]"}, target: ${parseFloat(i.toFixed(3))}`), B(t.sn) && !this.bitrateTest && (this.nextLoadPosition = t.start + t.duration), this.state = k.FRAG_LOADING;
    const d = this.config.progressive;
    let h;
    return d && o ? h = o.then((c) => !c || this.fragContextChanged(c.frag) ? null : this.fragmentLoader.load(t, s)).catch((c) => this.handleFragLoadError(c)) : h = Promise.all([this.fragmentLoader.load(t, d ? s : void 0), o]).then(([c]) => (!d && s && s(c), c)).catch((c) => this.handleFragLoadError(c)), this.hls.trigger(E.FRAG_LOADING, {
      frag: t,
      targetBufferTime: i
    }), this.fragCurrent === null ? Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")) : h;
  }
  doFragPartsLoad(t, e, i, s) {
    return new Promise((r, a) => {
      var o;
      const u = [], l = (o = i.details) == null ? void 0 : o.partList, d = (h) => {
        this.fragmentLoader.loadPart(t, h, s).then((c) => {
          u[h.index] = c;
          const f = c.part;
          this.hls.trigger(E.FRAG_LOADED, c);
          const g = Fi(i.details, t.sn, h.index + 1) || Os(l, t.sn, h.index + 1);
          if (g)
            d(g);
          else
            return r({
              frag: t,
              part: f,
              partsLoaded: u
            });
        }).catch(a);
      };
      d(e);
    });
  }
  handleFragLoadError(t) {
    if ("data" in t) {
      const e = t.data;
      e.frag && e.details === D.INTERNAL_ABORTED ? this.handleFragLoadAborted(e.frag, e.part) : e.frag && e.type === Y.KEY_SYSTEM_ERROR ? (e.frag.abortRequests(), this.resetStartWhenNotLoaded(), this.resetFragmentLoading(e.frag)) : this.hls.trigger(E.ERROR, e);
    } else
      this.hls.trigger(E.ERROR, {
        type: Y.OTHER_ERROR,
        details: D.INTERNAL_EXCEPTION,
        err: t,
        error: t,
        fatal: !0
      });
    return null;
  }
  _handleTransmuxerFlush(t) {
    const e = this.getCurrentContext(t);
    if (!e || 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: r
    } = e, 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, r, t.partial);
  }
  shouldLoadParts(t, e) {
    if (this.config.lowLatencyMode) {
      if (!t)
        return this.loadingParts;
      if (t.partList) {
        var i;
        const r = t.partList[0];
        if (r.fragment.type === W.SUBTITLE)
          return !1;
        const a = r.end + (((i = t.fragmentHint) == null ? void 0 : i.duration) || 0);
        if (e >= a) {
          var s;
          if ((this.hls.hasEnoughToStart ? ((s = this.media) == null ? void 0 : s.currentTime) || this.lastCurrentTime : this.getLoadPosition()) > r.start - r.fragment.duration)
            return !0;
        }
      }
    }
    return !1;
  }
  getCurrentContext(t) {
    const {
      levels: e,
      fragCurrent: i
    } = this, {
      level: s,
      sn: r,
      part: a
    } = t;
    if (!(e != null && e[s]))
      return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`), null;
    const o = e[s], u = o.details, l = a > -1 ? Fi(u, r, a) : null, d = l ? l.fragment : ks(u, r, i);
    return d ? (i && i !== d && (d.stats = i.stats), {
      frag: d,
      part: l,
      level: o
    }) : null;
  }
  bufferFragmentData(t, e, i, s, r) {
    if (this.state !== k.PARSING)
      return;
    const {
      data1: a,
      data2: o
    } = t;
    let u = a;
    if (o && (u = mt(a, o)), !u.length)
      return;
    const l = this.initPTS[e.cc], d = l ? -l.baseTime / l.timescale : void 0, h = {
      type: t.type,
      frag: e,
      part: i,
      chunkMeta: s,
      offset: d,
      parent: e.type,
      data: u
    };
    if (this.hls.trigger(E.BUFFER_APPENDING, h), t.dropped && t.independent && !i) {
      if (r)
        return;
      this.flushBufferGap(e);
    }
  }
  flushBufferGap(t) {
    const e = this.media;
    if (!e)
      return;
    if (!q.isBuffered(e, e.currentTime)) {
      this.flushMainBuffer(0, t.start);
      return;
    }
    const i = e.currentTime, s = q.bufferInfo(e, i, 0), r = t.duration, a = Math.min(this.config.maxFragLookUpTolerance * 2, r * 0.25), o = Math.max(Math.min(t.start - a, s.end - a), i + a);
    t.start - o > a && this.flushMainBuffer(o, t.start);
  }
  getFwdBufferInfo(t, e) {
    var i;
    const s = this.getLoadPosition();
    if (!B(s))
      return null;
    const a = this.lastCurrentTime > s || (i = this.media) != null && i.paused ? 0 : this.config.maxBufferHole;
    return this.getFwdBufferInfoAtPos(t, s, e, a);
  }
  getFwdBufferInfoAtPos(t, e, i, s) {
    const r = q.bufferInfo(t, e, s);
    if (r.len === 0 && r.nextStart !== void 0) {
      const a = this.fragmentTracker.getBufferedFrag(e, i);
      if (a && (r.nextStart <= a.end || a.gap)) {
        const o = Math.max(Math.min(r.nextStart, a.end) - e, s);
        return q.bufferInfo(t, e, o);
      }
    }
    return r;
  }
  getMaxBufferLength(t) {
    const {
      config: e
    } = this;
    let i;
    return t ? i = Math.max(8 * e.maxBufferSize / t, e.maxBufferLength) : i = e.maxBufferLength, Math.min(i, e.maxMaxBufferLength);
  }
  reduceMaxBufferLength(t, e) {
    const i = this.config, s = Math.max(Math.min(t - e, i.maxBufferLength), e), r = Math.max(t - e * 3, i.maxMaxBufferLength / 2, s);
    return r >= s ? (i.maxMaxBufferLength = r, this.warn(`Reduce max buffer length to ${r}s`), !0) : !1;
  }
  getAppendedFrag(t, e = W.MAIN) {
    const i = this.fragmentTracker ? this.fragmentTracker.getAppendedFrag(t, e) : null;
    return i && "fragment" in i ? i.fragment : i;
  }
  getNextFragment(t, e) {
    const i = e.fragments, s = i.length;
    if (!s)
      return null;
    const {
      config: r
    } = this, a = i[0].start, o = r.lowLatencyMode && !!e.partList;
    let u = null;
    if (e.live) {
      const h = r.initialLiveManifestSize;
      if (s < h)
        return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`), null;
      if (!e.PTSKnown && !this.startFragRequested && this.startPosition === -1 || t < a) {
        var l;
        o && !this.loadingParts && (this.log("LL-Part loading ON for initial live fragment"), this.loadingParts = !0), u = this.getInitialLiveFragment(e);
        const c = this.hls.startPosition, f = this.hls.liveSyncPosition, g = u ? (c !== -1 && c >= a ? c : f) || u.start : t;
        this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${c} liveSyncPosition: ${f} frag.start: ${(l = u) == null ? void 0 : l.start}`), this.startPosition = this.nextLoadPosition = g;
      }
    } else t <= a && (u = i[0]);
    if (!u) {
      const h = this.loadingParts ? e.partEnd : e.fragmentEnd;
      u = this.getFragmentAtPosition(t, h, e);
    }
    let d = this.filterReplacedPrimary(u, e);
    if (!d && u) {
      const h = u.sn - e.startSN;
      d = this.filterReplacedPrimary(i[h + 1] || null, e);
    }
    return this.mapToInitFragWhenRequired(d);
  }
  isLoopLoading(t, e) {
    const i = this.fragmentTracker.getState(t);
    return (i === lt.OK || i === lt.PARTIAL && !!t.gap) && this.nextLoadPosition > e;
  }
  getNextFragmentLoopLoading(t, e, i, s, r) {
    let a = null;
    if (t.gap && (a = this.getNextFragment(this.nextLoadPosition, e), 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 >= r) {
        const u = a.sn;
        return this.loopSn !== u && (this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${u}`), this.loopSn = u), null;
      }
    }
    return this.loopSn = void 0, a;
  }
  get primaryPrefetch() {
    return Hi(this.config), !1;
  }
  filterReplacedPrimary(t, e) {
    return t && (Hi(this.config), t);
  }
  mapToInitFragWhenRequired(t) {
    return t != null && t.initSegment && !t.initSegment.data && !this.bitrateTest ? t.initSegment : t;
  }
  getNextPart(t, e, i) {
    let s = -1, r = !1, a = !0;
    for (let o = 0, u = t.length; o < u; o++) {
      const l = t[o];
      if (a = a && !l.independent, s > -1 && i < l.start)
        break;
      const d = l.loaded;
      d ? s = -1 : (r || (l.independent || a) && l.fragment === e) && (l.fragment !== e && this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`), s = o), r = d;
    }
    return s;
  }
  loadedEndOfParts(t, e) {
    let i;
    for (let s = t.length; s--; ) {
      if (i = t[s], !i.loaded)
        return !1;
      if (e > 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(t) {
    const e = t.fragments, i = this.fragPrevious;
    let s = null;
    if (i) {
      if (t.hasProgramDateTime && (this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`), s = qr(e, i.endProgramDateTime, this.config.maxFragLookUpTolerance)), !s) {
        const r = i.sn + 1;
        if (r >= t.startSN && r <= t.endSN) {
          const a = e[r - t.startSN];
          i.cc === a.cc && (s = a, this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`));
        }
        s || (s = Qr(t, i.cc, i.end), s && this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`));
      }
    } else {
      const r = this.hls.liveSyncPosition;
      r !== null && (s = this.getFragmentAtPosition(r, this.bitrateTest ? t.fragmentEnd : t.edge, t));
    }
    return s;
  }
  /*
  This method finds the best matching fragment given the provided position.
   */
  getFragmentAtPosition(t, e, i) {
    const {
      config: s
    } = this;
    let {
      fragPrevious: r
    } = this, {
      fragments: a,
      endSN: o
    } = i;
    const {
      fragmentHint: u
    } = i, {
      maxFragLookUpTolerance: l
    } = s, d = i.partList, h = !!(this.loadingParts && d != null && d.length && u);
    h && !this.bitrateTest && d[d.length - 1].fragment.sn === u.sn && (a = a.concat(u), o = u.sn);
    let c;
    if (t < e) {
      var f;
      const p = t < this.lastCurrentTime || t > e - l || (f = this.media) != null && f.paused || !this.startFragRequested ? 0 : l;
      c = Ze(r, a, t, p);
    } else
      c = a[a.length - 1];
    if (c) {
      const g = c.sn - i.startSN, p = this.fragmentTracker.getState(c);
      if ((p === lt.OK || p === lt.PARTIAL && c.gap) && (r = c), r && c.sn === r.sn && (!h || d[0].fragment.sn > c.sn || !i.live) && c.level === r.level) {
        const y = a[g + 1];
        c.sn < o && this.fragmentTracker.getState(y) !== lt.OK ? c = y : c = null;
      }
    }
    return c;
  }
  alignPlaylists(t, e, i) {
    const s = t.fragments.length;
    if (!s)
      return this.warn("No fragments in live playlist"), 0;
    const r = t.fragmentStart, a = !e, o = t.alignedSliding && B(r);
    if (a || !o && !r) {
      Cn(i, t);
      const u = t.fragmentStart;
      return this.log(`Live playlist sliding: ${u.toFixed(2)} start-sn: ${e ? e.startSN : "na"}->${t.startSN} fragments: ${s}`), u;
    }
    return r;
  }
  waitForCdnTuneIn(t) {
    return t.live && t.canBlockReload && t.partTarget && t.tuneInGoal > Math.max(t.partHoldBack, t.partTarget * 3);
  }
  setStartPosition(t, e) {
    let i = this.startPosition;
    i < e && (i = -1);
    const s = this.timelineOffset;
    if (i === -1) {
      const r = this.startTimeOffset !== null, a = r ? this.startTimeOffset : t.startTimeOffset;
      a !== null && B(a) ? (i = e + a, a < 0 && (i += t.edge), i = Math.min(Math.max(e, i), e + t.totalduration), this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${r ? "multivariant" : "media"} playlist`), this.startPosition = i) : t.live ? (i = this.hls.liveSyncPosition || e, 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 t;
    const {
      media: e
    } = this;
    let i = 0;
    return (t = this.hls) != null && t.hasEnoughToStart && e ? i = e.currentTime : this.nextLoadPosition >= 0 && (i = this.nextLoadPosition), i;
  }
  handleFragLoadAborted(t, e) {
    this.transmuxer && t.type === this.playlistType && ft(t) && t.stats.aborted && (this.log(`Fragment ${t.sn}${e ? " part " + e.index : ""} of ${this.playlistLabel()} ${t.level} was aborted`), this.resetFragmentLoading(t));
  }
  resetFragmentLoading(t) {
    (!this.fragCurrent || !this.fragContextChanged(t) && this.state !== k.FRAG_LOADING_WAITING_RETRY) && (this.state = k.IDLE);
  }
  onFragmentOrKeyLoadError(t, e) {
    var i;
    if (e.chunkMeta && !e.frag) {
      const y = this.getCurrentContext(e.chunkMeta);
      y && (e.frag = y.frag);
    }
    const s = e.frag;
    if (!s || s.type !== t || !this.levels)
      return;
    if (this.fragContextChanged(s)) {
      var r;
      this.warn(`Frag load error must match current frag to retry ${s.url} > ${(r = this.fragCurrent) == null ? void 0 : r.url}`);
      return;
    }
    const a = e.details === D.FRAG_GAP;
    a && this.fragmentTracker.fragBuffered(s, !0);
    const o = e.errorAction;
    if (!o) {
      this.state = k.ERROR;
      return;
    }
    const {
      action: u,
      flags: l,
      retryCount: d = 0,
      retryConfig: h
    } = o, c = !!h, f = c && u === at.RetryRequest, g = c && !o.resolved && l === ut.MoveAllAlternatesMatchingHost, p = (i = this.hls.latestLevelDetails) == null ? void 0 : i.live;
    if (!f && g && ft(s) && !s.endList && p && !As(e))
      this.resetFragmentErrors(t), this.treatAsGap(s), o.resolved = !0;
    else if ((f || g) && d < h.maxNumRetry) {
      var m;
      const y = Ve((m = e.response) == null ? void 0 : m.code), T = Je(h, d);
      if (this.resetStartWhenNotLoaded(), this.retryDate = self.performance.now() + T, this.state = k.FRAG_LOADING_WAITING_RETRY, o.resolved = !0, y) {
        this.log("Waiting for connection (offline)"), this.retryDate = 1 / 0, e.reason = "offline";
        return;
      }
      this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d + 1}/${h.maxNumRetry} in ${T}ms`);
    } else if (h)
      if (this.resetFragmentErrors(t), d < h.maxNumRetry)
        !a && u !== at.RemoveAlternatePermanently && (o.resolved = !0);
      else {
        this.warn(`${e.details} reached or exceeded max retry (${d})`);
        return;
      }
    else u === at.SendAlternateToPenaltyBox ? this.state = k.WAITING_LEVEL : this.state = k.ERROR;
    this.tickImmediate();
  }
  checkRetryDate() {
    const t = self.performance.now(), e = this.retryDate, i = e === 1 / 0;
    (!e || t >= e || i && !Ve(0)) && (i && this.log("Connection restored (online)"), this.resetStartWhenNotLoaded(), this.state = k.IDLE);
  }
  reduceLengthAndFlushBuffer(t) {
    if (this.state === k.PARSING || this.state === k.PARSED) {
      const e = t.frag, i = t.parent, s = this.getFwdBufferInfo(this.mediaBuffer, i), r = s && s.len > 0.5;
      r && this.reduceMaxBufferLength(s.len, e?.duration || 10);
      const a = !r;
      return a && this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`), e && (this.fragmentTracker.removeFragment(e), this.nextLoadPosition = e.start), this.resetLoadingState(), a;
    }
    return !1;
  }
  resetFragmentErrors(t) {
    t === W.AUDIO && (this.fragCurrent = null), this.hls.hasEnoughToStart || (this.startFragRequested = !1), this.state !== k.STOPPED && (this.state = k.IDLE);
  }
  afterBufferFlushed(t, e, i) {
    if (!t)
      return;
    const s = q.getBuffered(t);
    this.fragmentTracker.detectEvictedFragments(e, 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 t = this.levelLastLoaded, e = t ? t.details : null;
      e != null && e.live ? (this.log("resetting startPosition for live start"), this.startPosition = -1, this.setStartPosition(e, e.fragmentStart), this.resetLoadingState()) : this.nextLoadPosition = this.startPosition;
    }
  }
  resetWhenMissingContext(t) {
    this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level === -1 ? "<removed>" : t.level}. This chunk will not be buffered.`), this.removeUnbufferedFrags(), this.resetStartWhenNotLoaded(), this.resetLoadingState();
  }
  removeUnbufferedFrags(t = 0) {
    this.fragmentTracker.removeFragmentsInRange(t, 1 / 0, this.playlistType, !1, !0);
  }
  updateLevelTiming(t, e, i, s) {
    const r = i.details;
    if (!r) {
      this.warn("level.details undefined");
      return;
    }
    if (!Object.keys(t.elementaryStreams).reduce((u, l) => {
      const d = t.elementaryStreams[l];
      if (d) {
        const h = d.endPTS - d.startPTS;
        if (h <= 0)
          return this.warn(`Could not parse fragment ${t.sn} ${l} duration reliably (${h})`), u || !1;
        const c = s ? 0 : Cs(r, t, d.startPTS, d.endPTS, d.startDTS, d.endDTS, this);
        return this.hls.trigger(E.LEVEL_PTS_UPDATED, {
          details: r,
          level: i,
          drift: c,
          type: l,
          frag: t,
          start: d.startPTS,
          end: d.endPTS
        }), !0;
      }
      return u;
    }, !1)) {
      var o;
      if (i.fragmentError === 0 && this.treatAsGap(t, i), ((o = this.transmuxer) == null ? void 0 : o.error) === null) {
        const u = new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);
        if (this.warn(u.message), this.hls.trigger(E.ERROR, {
          type: Y.MEDIA_ERROR,
          details: D.FRAG_PARSING_ERROR,
          fatal: !1,
          error: u,
          frag: t,
          reason: `Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`
        }), !this.hls)
          return;
        this.resetTransmuxer();
      }
    }
    this.state = k.PARSED, this.log(`Parsed ${t.type} sn: ${t.sn}${e ? " part: " + e.index : ""} of ${this.fragInfo(t, !1, e)})`), this.hls.trigger(E.FRAG_PARSED, {
      frag: t,
      part: e
    });
  }
  playlistLabel() {
    return this.playlistType === W.MAIN ? "level" : "track";
  }
  fragInfo(t, e = !0, i) {
    var s, r;
    return `${this.playlistLabel()} ${t.level} (${i ? "part" : "frag"}:[${((s = e && !i ? t.startPTS : (i || t).start) != null ? s : NaN).toFixed(3)}-${((r = e && !i ? t.endPTS : (i || t).end) != null ? r : NaN).toFixed(3)}]${i && t.type === "main" ? "INDEPENDENT=" + (i.independent ? "YES" : "NO") : ""}`;
  }
  treatAsGap(t, e) {
    e && e.fragmentError++, t.gap = !0, this.fragmentTracker.removeFragment(t), this.fragmentTracker.fragBuffered(t, !0);
  }
  resetTransmuxer() {
    var t;
    (t = this.transmuxer) == null || t.reset();
  }
  recoverWorkerError(t) {
    t.event === "demuxerWorker" && (this.fragmentTracker.removeAllFragments(), this.transmuxer && (this.transmuxer.destroy(), this.transmuxer = null), this.resetStartWhenNotLoaded(), this.resetLoadingState());
  }
  set state(t) {
    const e = this._state;
    e !== t && (this._state = t, this.log(`${e}->${t}`));
  }
  get state() {
    return this._state;
  }
}
function Hi(n) {
  return !1;
}
class wn {
  constructor(t) {
    this.tracks = void 0, this.queues = {
      video: [],
      audio: [],
      audiovideo: []
    }, this.tracks = t;
  }
  destroy() {
    this.tracks = this.queues = null;
  }
  append(t, e, i) {
    if (this.queues === null || this.tracks === null)
      return;
    const s = this.queues[e];
    s.push(t), s.length === 1 && !i && this.executeNext(e);
  }
  appendBlocker(t) {
    return new Promise((e) => {
      const i = {
        label: "async-blocker",
        execute: e,
        onStart: () => {
        },
        onComplete: () => {
        },
        onError: () => {
        }
      };
      this.append(i, t);
    });
  }
  prependBlocker(t) {
    return new Promise((e) => {
      if (this.queues) {
        const i = {
          label: "async-blocker-prepend",
          execute: e,
          onStart: () => {
          },
          onComplete: () => {
          },
          onError: () => {
          }
        };
        this.queues[t].unshift(i);
      }
    });
  }
  removeBlockers() {
    this.queues !== null && [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach((t) => {
      var e;
      const i = (e = t[0]) == null ? void 0 : e.label;
      (i === "async-blocker" || i === "async-blocker-prepend") && (t[0].execute(), t.splice(0, 1));
    });
  }
  unblockAudio(t) {
    if (this.queues === null)
      return;
    this.queues.audio[0] === t && this.shiftAndExecuteNext("audio");
  }
  executeNext(t) {
    if (this.queues === null || this.tracks === null)
      return;
    const e = this.queues[t];
    if (e.length) {
      const s = e[0];
      try {
        s.execute();
      } catch (r) {
        var i;
        if (s.onError(r), this.queues === null || this.tracks === null)
          return;
        const a = (i = this.tracks[t]) == null ? void 0 : i.buffer;
        a != null && a.updating || this.shiftAndExecuteNext(t);
      }
    }
  }
  shiftAndExecuteNext(t) {
    this.queues !== null && (this.queues[t].shift(), this.executeNext(t));
  }
  current(t) {
    var e;
    return ((e = this.queues) == null ? void 0 : e[t][0]) || null;
  }
  toString() {
    const {
      queues: t,
      tracks: e
    } = this;
    return t === null || e === null ? "<destroyed>" : `
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`;
  }
  list(t) {
    var e, i;
    return (e = this.queues) != null && e[t] || (i = this.tracks) != null && i[t] ? `${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}` : "";
  }
  listSbInfo(t) {
    var e;
    const i = (e = this.tracks) == null ? void 0 : e[t], s = i?.buffer;
    return s ? `SourceBuffer${s.updating ? " updating" : ""}${i.ended ? " ended" : ""}${i.ending ? " ending" : ""}` : "none";
  }
  listOps(t) {
    var e;
    return ((e = this.queues) == null ? void 0 : e[t].map((i) => i.label).join(", ")) || "";
  }
}
const Ki = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/, Bs = "HlsJsTrackRemovedError";
class Fn extends Error {
  constructor(t) {
    super(t), this.name = Bs;
  }
}
class Mn extends Rt {
  constructor(t, e) {
    super("buffer-controller", t.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: r
      } = this;
      i && this.log("Media source opened"), !(!s || !r) && (r.removeEventListener("sourceopen", this._onMediaSourceOpen), s.removeEventListener("emptied", this._onMediaEmptied), this.updateDuration(), this.hls.trigger(E.MEDIA_ATTACHED, {
        media: s,
        mediaSource: r
      }), 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 = t, this.fragmentTracker = e, this.appendSource = vr(_t(t.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: t
    } = this;
    t.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.MANIFEST_PARSED, this.onManifestParsed, this), t.on(E.BUFFER_RESET, this.onBufferReset, this), t.on(E.BUFFER_APPENDING, this.onBufferAppending, this), t.on(E.BUFFER_CODECS, this.onBufferCodecs, this), t.on(E.BUFFER_EOS, this.onBufferEos, this), t.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), t.on(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.on(E.FRAG_PARSED, this.onFragParsed, this), t.on(E.FRAG_CHANGED, this.onFragChanged, this), t.on(E.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.MANIFEST_PARSED, this.onManifestParsed, this), t.off(E.BUFFER_RESET, this.onBufferReset, this), t.off(E.BUFFER_APPENDING, this.onBufferAppending, this), t.off(E.BUFFER_CODECS, this.onBufferCodecs, this), t.off(E.BUFFER_EOS, this.onBufferEos, this), t.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), t.off(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.off(E.FRAG_PARSED, this.onFragParsed, this), t.off(E.FRAG_CHANGED, this.onFragChanged, this), t.off(E.ERROR, this.onError, this);
  }
  transferMedia() {
    const {
      media: t,
      mediaSource: e
    } = this;
    if (!t)
      return null;
    const i = {};
    if (this.operationQueue) {
      const r = this.isUpdating();
      r || this.operationQueue.removeBlockers();
      const a = this.isQueued();
      (r || a) && this.warn(`Transfering MediaSource with${a ? " operations in queue" : ""}${r ? " updating SourceBuffer(s)" : ""} ${this.operationQueue}`), this.operationQueue.destroy();
    }
    const s = this.transferData;
    return !this.sourceBufferCount && s && s.mediaSource === e ? nt(i, s.tracks) : this.sourceBuffers.forEach((r) => {
      const [a] = r;
      a && (i[a] = nt({}, this.tracks[a]), this.removeBuffer(a)), r[0] = r[1] = null;
    }), {
      media: t,
      mediaSource: e,
      tracks: i
    };
  }
  initTracks() {
    const t = {};
    this.sourceBuffers = [[null, null], [null, null]], this.tracks = t, this.resetQueue(), this.resetAppendErrors(), this.lastMpegAudioChunk = this.blockedAudioAppend = null, this.lastVideoAppendEnd = 0;
  }
  onManifestLoading() {
    this.bufferCodecEventsTotal = 0, this.details = null;
  }
  onManifestParsed(t, e) {
    var i;
    let s = 2;
    (e.audio && !e.video || !e.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(t, e) {
    const i = this.media = e.media;
    this.transferData = this.overrides = void 0;
    const s = _t(this.appendSource);
    if (s) {
      const r = !!e.mediaSource;
      (r || e.overrides) && (this.transferData = e, this.overrides = e.overrides);
      const a = this.mediaSource = e.mediaSource || new s();
      if (this.assignMediaSource(a), r)
        this._objectUrl = i.src, this.attachTransferred();
      else {
        const o = this._objectUrl = self.URL.createObjectURL(a);
        if (this.appendSource)
          try {
            i.removeAttribute("src");
            const u = self.ManagedMediaSource;
            i.disableRemotePlayback = i.disableRemotePlayback || u && a instanceof u, Wi(i), Nn(i, o), i.load();
          } catch {
            i.src = o;
          }
        else
          i.src = o;
      }
      i.addEventListener("emptied", this._onMediaEmptied);
    }
  }
  assignMediaSource(t) {
    var e, i;
    this.log(`${((e = this.transferData) == null ? void 0 : e.mediaSource) === t ? "transferred" : "created"} media source: ${(i = t.constructor) == null ? void 0 : i.name}`), t.addEventListener("sourceopen", this._onMediaSourceOpen), t.addEventListener("sourceended", this._onMediaSourceEnded), t.addEventListener("sourceclose", this._onMediaSourceClose), this.appendSource && (t.addEventListener("startstreaming", this._onStartStreaming), t.addEventListener("endstreaming", this._onEndStreaming));
  }
  attachTransferred() {
    const t = this.media, e = this.transferData;
    if (!e || !t)
      return;
    const i = this.tracks, s = e.tracks, r = s ? Object.keys(s) : null, a = r ? r.length : 0, o = () => {
      Promise.resolve().then(() => {
        this.media && this.mediaSourceOpenOrEnded && this._onMediaSourceOpen();
      });
    };
    if (s && r && 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: ${ot(i, (u, l) => u === "initSegment" ? void 0 : l)};
transfer tracks: ${ot(s, (u, l) => u === "initSegment" ? void 0 : l)}}`), !yr(s, i)) {
        e.mediaSource = null, e.tracks = void 0;
        const u = t.currentTime, l = this.details, d = Math.max(u, l?.fragments[0].start || 0);
        if (d - u > 1) {
          this.log(`attachTransferred: waiting for playback to reach new tracks start time ${u} -> ${d}`);
          return;
        }
        this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${d} currentTime: ${u}`), this.onMediaDetaching(E.MEDIA_DETACHING, {}), this.onMediaAttaching(E.MEDIA_ATTACHING, e), t.currentTime = d;
        return;
      }
      this.transferData = void 0, r.forEach((u) => {
        const l = u, d = s[l];
        if (d) {
          const h = d.buffer;
          if (h) {
            const c = this.fragmentTracker, f = d.id;
            if (c.hasFragments(f) || c.hasParts(f)) {
              const m = q.getBuffered(h);
              c.detectEvictedFragments(l, m, f, null, !0);
            }
            const g = De(l), p = [l, h];
            this.sourceBuffers[g] = p, 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 t;
    const e = (t = this.mediaSource) == null ? void 0 : t.readyState;
    return e === "open" || e === "ended";
  }
  onMediaDetaching(t, e) {
    const i = !!e.transferMedia;
    this.transferData = this.overrides = void 0;
    const {
      media: s,
      mediaSource: r,
      _objectUrl: a
    } = this;
    if (r) {
      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 = r.readyState === "open";
          try {
            const u = r.sourceBuffers;
            for (let l = u.length; l--; )
              o && u[l].abort(), r.removeSourceBuffer(u[l]);
            o && r.endOfStream();
          } catch (u) {
            this.warn(`onMediaDetaching: ${u.message} while calling endOfStream`);
          }
        }
        this.sourceBufferCount && this.onBufferReset();
      }
      r.removeEventListener("sourceopen", this._onMediaSourceOpen), r.removeEventListener("sourceended", this._onMediaSourceEnded), r.removeEventListener("sourceclose", this._onMediaSourceClose), this.appendSource && (r.removeEventListener("startstreaming", this._onStartStreaming), r.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 && Wi(s), s.load()) : this.warn("media|source.src was changed by a third party - skip cleanup")), this.media = null), this.hls.trigger(E.MEDIA_DETACHED, e);
  }
  onBufferReset() {
    this.sourceBuffers.forEach(([t]) => {
      t && this.resetBuffer(t);
    }), this.initTracks();
  }
  resetBuffer(t) {
    var e;
    const i = (e = this.tracks[t]) == null ? void 0 : e.buffer;
    if (this.removeBuffer(t), i)
      try {
        var s;
        (s = this.mediaSource) != null && s.sourceBuffers.length && this.mediaSource.removeSourceBuffer(i);
      } catch (r) {
        this.warn(`onBufferReset ${t}`, r);
      }
    delete this.tracks[t];
  }
  removeBuffer(t) {
    this.removeBufferListeners(t), this.sourceBuffers[De(t)] = [null, null];
    const e = this.tracks[t];
    e && (e.buffer = void 0);
  }
  resetQueue() {
    this.operationQueue && this.operationQueue.destroy(), this.operationQueue = new wn(this.tracks);
  }
  onBufferCodecs(t, e) {
    var i;
    const s = this.tracks, r = Object.keys(e);
    this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);
    const a = "audiovideo" in e && (s.audio || s.video) || s.audiovideo && ("audio" in e || "video" in e), o = !a && this.sourceBufferCount && this.media && r.some((u) => !s[u]);
    if (a || o) {
      this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);
      return;
    }
    r.forEach((u) => {
      var l, d;
      const h = e[u], {
        id: c,
        codec: f,
        levelCodec: g,
        container: p,
        metadata: m,
        supplemental: y
      } = h;
      let T = s[u];
      const v = (l = this.transferData) == null || (l = l.tracks) == null ? void 0 : l[u], x = v != null && v.buffer ? v : T, A = x?.pendingCodec || x?.codec, C = x?.levelCodec;
      T || (T = s[u] = {
        buffer: void 0,
        listeners: [],
        codec: f,
        supplemental: y,
        container: p,
        levelCodec: g,
        metadata: m,
        id: c
      });
      const S = le(A, C), R = S?.replace(Ki, "$1");
      let b = le(f, g);
      const I = (d = b) == null ? void 0 : d.replace(Ki, "$1");
      b && S && R !== I && (u.slice(0, 5) === "audio" && (b = ce(b, this.appendSource)), this.log(`switching codec ${A} to ${b}`), b !== (T.pendingCodec || T.codec) && (T.pendingCodec = b), T.container = p, this.appendChangeType(u, p, b));
    }), (this.tracksReady || this.sourceBufferCount) && (e.tracks = this.sourceBufferTracks), !this.sourceBufferCount && (this.bufferCodecEventsTotal > 1 && !this.tracks.video && !e.video && ((i = e.audio) == null ? void 0 : i.id) === "main" && (this.log("Main audio-only"), this.bufferCodecEventsTotal = 1), this.mediaSourceOpenOrEnded && this.checkPendingTracks());
  }
  get sourceBufferTracks() {
    return Object.keys(this.tracks).reduce((t, e) => {
      const i = this.tracks[e];
      return t[e] = {
        id: i.id,
        container: i.container,
        codec: i.codec,
        levelCodec: i.levelCodec
      }, t;
    }, {});
  }
  appendChangeType(t, e, i) {
    const s = `${e};codecs=${i}`, r = {
      label: `change-type=${s}`,
      execute: () => {
        const a = this.tracks[t];
        if (a) {
          const o = a.buffer;
          o != null && o.changeType && (this.log(`changing ${t} sourceBuffer type to ${s}`), o.changeType(s), a.codec = i, a.container = e);
        }
        this.shiftAndExecuteNext(t);
      },
      onStart: () => {
      },
      onComplete: () => {
      },
      onError: (a) => {
        this.warn(`Failed to change ${t} SourceBuffer type`, a);
      }
    };
    this.append(r, t, this.isPending(this.tracks[t]));
  }
  blockAudio(t) {
    var e;
    const i = t.start, s = i + t.duration * 0.05;
    if (((e = this.fragmentTracker.getAppendedFrag(i, W.MAIN)) == null ? void 0 : e.gap) === !0)
      return;
    const a = {
      label: "block-audio",
      execute: () => {
        var o;
        const u = this.tracks.video;
        (this.lastVideoAppendEnd > s || u != null && u.buffer && q.isBuffered(u.buffer, s) || ((o = this.fragmentTracker.getAppendedFrag(s, W.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: t
    }, this.append(a, "audio", !0);
  }
  unblockAudio() {
    const {
      blockedAudioAppend: t,
      operationQueue: e
    } = this;
    t && e && (this.blockedAudioAppend = null, e.unblockAudio(t.op));
  }
  onBufferAppending(t, e) {
    const {
      tracks: i
    } = this, {
      data: s,
      type: r,
      parent: a,
      frag: o,
      part: u,
      chunkMeta: l,
      offset: d
    } = e, h = l.buffering[r], {
      sn: c,
      cc: f
    } = o, g = self.performance.now();
    h.start = g;
    const p = o.stats.buffering, m = u ? u.stats.buffering : null;
    p.start === 0 && (p.start = g), m && m.start === 0 && (m.start = g);
    const y = i.audio;
    let T = !1;
    r === "audio" && y?.container === "audio/mpeg" && (T = !this.lastMpegAudioChunk || l.id === 1 || this.lastMpegAudioChunk.sn !== l.sn, this.lastMpegAudioChunk = l);
    const v = i.video, x = v?.buffer;
    if (x && c !== "initSegment") {
      const S = u || o, R = this.blockedAudioAppend;
      if (r === "audio" && a !== "main" && !this.blockedAudioAppend && !(v.ending || v.ended)) {
        const I = S.start + S.duration * 0.05, _ = x.buffered, F = this.currentOp("video");
        !_.length && !F ? this.blockAudio(S) : !F && !q.isBuffered(x, I) && this.lastVideoAppendEnd < I && this.blockAudio(S);
      } else if (r === "video") {
        const b = S.end;
        if (R) {
          const I = R.frag.start;
          (b > I || b < this.lastVideoAppendEnd || q.isBuffered(x, I)) && this.unblockAudio();
        }
        this.lastVideoAppendEnd = b;
      }
    }
    const A = (u || o).start, C = {
      label: `append-${r}`,
      execute: () => {
        var S;
        h.executeStart = self.performance.now();
        const R = (S = this.tracks[r]) == null ? void 0 : S.buffer;
        R && (T ? this.updateTimestampOffset(R, A, 0.1, r, c, f) : d !== void 0 && B(d) && this.updateTimestampOffset(R, d, 1e-6, r, c, f)), this.appendExecutor(s, r);
      },
      onStart: () => {
      },
      onComplete: () => {
        const S = self.performance.now();
        h.executeEnd = h.end = S, p.first === 0 && (p.first = S), m && m.first === 0 && (m.first = S);
        const R = {};
        this.sourceBuffers.forEach(([b, I]) => {
          b && (R[b] = q.getBuffered(I));
        }), this.appendErrors[r] = 0, r === "audio" || r === "video" ? this.appendErrors.audiovideo = 0 : (this.appendErrors.audio = 0, this.appendErrors.video = 0), this.hls.trigger(E.BUFFER_APPENDED, {
          type: r,
          frag: o,
          part: u,
          chunkMeta: l,
          parent: o.type,
          timeRanges: R
        });
      },
      onError: (S) => {
        var R;
        const b = {
          type: Y.MEDIA_ERROR,
          parent: o.type,
          details: D.BUFFER_APPEND_ERROR,
          sourceBufferName: r,
          frag: o,
          part: u,
          chunkMeta: l,
          error: S,
          err: S,
          fatal: !1
        }, I = (R = this.media) == null ? void 0 : R.error;
        if (S.code === DOMException.QUOTA_EXCEEDED_ERR || S.name == "QuotaExceededError" || "quota" in S)
          b.details = D.BUFFER_FULL_ERROR;
        else if (S.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !I)
          b.errorAction = Wt(!0);
        else if (S.name === Bs && this.sourceBufferCount === 0)
          b.errorAction = Wt(!0);
        else {
          const _ = ++this.appendErrors[r];
          this.warn(`Failed ${_}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I || "no media error"})`), (_ >= this.hls.config.appendErrorMaxRetry || I) && (b.fatal = !0);
        }
        this.hls.trigger(E.ERROR, b);
      }
    };
    this.log(`queuing "${r}" append sn: ${c}${u ? " p: " + u.index : ""} of ${o.type === W.MAIN ? "level" : "track"} ${o.level} cc: ${f}`), this.append(C, r, this.isPending(this.tracks[r]));
  }
  getFlushOp(t, e, i) {
    return this.log(`queuing "${t}" remove ${e}-${i}`), {
      label: "remove",
      execute: () => {
        this.removeExecutor(t, e, i);
      },
      onStart: () => {
      },
      onComplete: () => {
        this.hls.trigger(E.BUFFER_FLUSHED, {
          type: t
        });
      },
      onError: (s) => {
        this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`, s);
      }
    };
  }
  onBufferFlushing(t, e) {
    const {
      type: i,
      startOffset: s,
      endOffset: r
    } = e;
    i ? this.append(this.getFlushOp(i, s, r), i) : this.sourceBuffers.forEach(([a]) => {
      a && this.append(this.getFlushOp(a, s, r), a);
    });
  }
  onFragParsed(t, e) {
    const {
      frag: i,
      part: s
    } = e, r = [], a = s ? s.elementaryStreams : i.elementaryStreams;
    a[tt.AUDIOVIDEO] ? r.push("audiovideo") : (a[tt.AUDIO] && r.push("audio"), a[tt.VIDEO] && r.push("video"));
    const o = () => {
      const u = self.performance.now();
      i.stats.buffering.end = u, s && (s.stats.buffering.end = u);
      const l = s ? s.stats : i.stats;
      this.hls.trigger(E.FRAG_BUFFERED, {
        frag: i,
        part: s,
        stats: l,
        id: i.type
      });
    };
    r.length === 0 && this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`), this.blockBuffers(o, r).catch((u) => {
      this.warn(`Fragment buffered callback ${u}`), this.stepOperationQueue(this.sourceBufferTypes);
    });
  }
  onFragChanged(t, e) {
    this.trimBuffers();
  }
  get bufferedToEnd() {
    return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([t]) => {
      if (t) {
        const e = this.tracks[t];
        if (e)
          return !e.ended || e.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(t, e) {
    var i;
    this.sourceBuffers.forEach(([a]) => {
      if (a) {
        const o = this.tracks[a];
        (!e.type || e.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(E.BUFFERED_TO_END, void 0);
    })) : (this.tracksEnded(), this.hls.trigger(E.BUFFERED_TO_END, void 0)) : e.type === "video" && this.unblockAudio();
  }
  tracksEnded() {
    this.sourceBuffers.forEach(([t]) => {
      if (t !== null) {
        const e = this.tracks[t];
        e && (e.ending = !1);
      }
    });
  }
  onLevelUpdated(t, {
    details: e
  }) {
    e.fragments.length && (this.details = e, this.updateDuration());
  }
  updateDuration() {
    this.blockUntilOpen(() => {
      const t = this.getDurationAndRange();
      t && this.updateMediaSource(t);
    });
  }
  onError(t, e) {
    if (e.details === D.BUFFER_APPEND_ERROR && e.frag) {
      var i;
      const s = (i = e.errorAction) == null ? void 0 : i.nextAutoLevel;
      B(s) && s !== e.frag.level && this.resetAppendErrors();
    }
  }
  resetAppendErrors() {
    this.appendErrors = {
      audio: 0,
      video: 0,
      audiovideo: 0
    };
  }
  trimBuffers() {
    const {
      hls: t,
      details: e,
      media: i
    } = this;
    if (!i || e === null || !this.sourceBufferCount)
      return;
    const s = t.config, r = i.currentTime, a = e.levelTargetDuration, o = e.live && s.liveBackBufferLength !== null ? s.liveBackBufferLength : s.backBufferLength;
    if (B(o) && o >= 0) {
      const l = Math.max(o, a), d = Math.floor(r / a) * a - l;
      this.flushBackBuffer(r, a, d);
    }
    const u = s.frontBufferFlushThreshold;
    if (B(u) && u > 0) {
      const l = Math.max(s.maxBufferLength, u), d = Math.max(l, a), h = Math.floor(r / a) * a + d;
      this.flushFrontBuffer(r, a, h);
    }
  }
  flushBackBuffer(t, e, i) {
    this.sourceBuffers.forEach(([s, r]) => {
      if (r) {
        const o = q.getBuffered(r);
        if (o.length > 0 && i > o.start(0)) {
          var a;
          this.hls.trigger(E.BACK_BUFFER_REACHED, {
            bufferEnd: i
          });
          const u = this.tracks[s];
          if ((a = this.details) != null && a.live)
            this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED, {
              bufferEnd: i
            });
          else if (u != null && u.ended) {
            this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);
            return;
          }
          this.hls.trigger(E.BUFFER_FLUSHING, {
            startOffset: 0,
            endOffset: i,
            type: s
          });
        }
      }
    });
  }
  flushFrontBuffer(t, e, i) {
    this.sourceBuffers.forEach(([s, r]) => {
      if (r) {
        const a = q.getBuffered(r), o = a.length;
        if (o < 2)
          return;
        const u = a.start(o - 1), l = a.end(o - 1);
        if (i > u || t >= u && t <= l)
          return;
        this.hls.trigger(E.BUFFER_FLUSHING, {
          startOffset: u,
          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 t;
    const {
      details: e,
      mediaSource: i
    } = this;
    if (!e || !this.media || i?.readyState !== "open")
      return null;
    const s = e.edge;
    if (e.live && this.hls.config.liveDurationInfinity) {
      if (e.fragments.length && i.setLiveSeekableRange) {
        const l = Math.max(0, e.fragmentStart), d = Math.max(l, s);
        return {
          duration: 1 / 0,
          start: l,
          end: d
        };
      }
      return {
        duration: 1 / 0
      };
    }
    const r = (t = this.overrides) == null ? void 0 : t.duration;
    if (r)
      return B(r) ? {
        duration: r
      } : null;
    const a = this.media.duration, o = B(i.duration) ? i.duration : 0;
    return s > o && s > a || !B(a) ? {
      duration: s
    } : null;
  }
  updateMediaSource({
    duration: t,
    start: e,
    end: i
  }) {
    const s = this.mediaSource;
    !this.media || !s || s.readyState !== "open" || (s.duration !== t && (B(t) && this.log(`Updating MediaSource duration to ${t.toFixed(3)}`), s.duration = t), e !== void 0 && i !== void 0 && (this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`), s.setLiveSeekableRange(e, i)));
  }
  get tracksReady() {
    const t = this.pendingTrackCount;
    return t > 0 && (t >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  }
  checkPendingTracks() {
    const {
      bufferCodecEventsTotal: t,
      pendingTrackCount: e,
      tracks: i
    } = this;
    if (this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${ot(i)}`), this.tracksReady) {
      var s;
      const r = (s = this.transferData) == null ? void 0 : s.tracks;
      r && Object.keys(r).length ? this.attachTransferred() : this.createSourceBuffers();
    }
  }
  bufferCreated() {
    if (this.sourceBufferCount) {
      const t = {};
      this.sourceBuffers.forEach(([e, i]) => {
        if (e) {
          const s = this.tracks[e];
          t[e] = {
            buffer: i,
            container: s.container,
            codec: s.codec,
            supplemental: s.supplemental,
            levelCodec: s.levelCodec,
            id: s.id,
            metadata: s.metadata
          };
        }
      }), this.hls.trigger(E.BUFFER_CREATED, {
        tracks: t
      }), this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`), this.sourceBuffers.forEach(([e]) => {
        this.executeNext(e);
      });
    } else {
      const t = new Error("could not create source buffer for media codec(s)");
      this.hls.trigger(E.ERROR, {
        type: Y.MEDIA_ERROR,
        details: D.BUFFER_INCOMPATIBLE_CODECS_ERROR,
        fatal: !0,
        error: t,
        reason: t.message
      });
    }
  }
  createSourceBuffers() {
    const {
      tracks: t,
      sourceBuffers: e,
      mediaSource: i
    } = this;
    if (!i)
      throw new Error("createSourceBuffers called when mediaSource was null");
    for (const r in t) {
      const a = r, o = t[a];
      if (this.isPending(o)) {
        const u = this.getTrackCodec(o, a), l = `${o.container};codecs=${u}`;
        o.codec = u, this.log(`creating sourceBuffer(${l})${this.currentOp(a) ? " Queued" : ""} ${ot(o)}`);
        try {
          const d = i.addSourceBuffer(l), h = De(a), c = [a, d];
          e[h] = c, 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(E.ERROR, {
            type: Y.MEDIA_ERROR,
            details: D.BUFFER_ADD_CODEC_ERROR,
            fatal: !1,
            error: d,
            sourceBufferName: a,
            mimeType: l,
            parent: o.id
          });
          return;
        }
        this.trackSourceBuffer(a, o);
      }
    }
    this.bufferCreated();
  }
  getTrackCodec(t, e) {
    const i = t.supplemental;
    let s = t.codec;
    i && (e === "video" || e === "audiovideo") && zt(i, "video") && (s = Nr(s, i));
    const r = le(s, t.levelCodec);
    return r ? e.slice(0, 5) === "audio" ? ce(r, this.appendSource) : r : "";
  }
  trackSourceBuffer(t, e) {
    const i = e.buffer;
    if (!i)
      return;
    const s = this.getTrackCodec(e, t);
    this.tracks[t] = {
      buffer: i,
      codec: s,
      container: e.container,
      levelCodec: e.levelCodec,
      supplemental: e.supplemental,
      metadata: e.metadata,
      id: e.id,
      listeners: []
    }, this.removeBufferListeners(t), this.addBufferListener(t, "updatestart", this.onSBUpdateStart), this.addBufferListener(t, "updateend", this.onSBUpdateEnd), this.addBufferListener(t, "error", this.onSBUpdateError), this.appendSource && this.addBufferListener(t, "bufferedchange", (r, a) => {
      const o = a.removedRanges;
      o != null && o.length && this.hls.trigger(E.BUFFER_FLUSHED, {
        type: r
      });
    });
  }
  get mediaSrc() {
    var t, e;
    const i = ((t = this.media) == null || (e = t.querySelector) == null ? void 0 : e.call(t, "source")) || this.media;
    return i?.src;
  }
  onSBUpdateStart(t) {
    const e = this.currentOp(t);
    e && e.onStart();
  }
  onSBUpdateEnd(t) {
    var e;
    if (((e = this.mediaSource) == null ? void 0 : e.readyState) === "closed") {
      this.resetBuffer(t);
      return;
    }
    const i = this.currentOp(t);
    i && (i.onComplete(), this.shiftAndExecuteNext(t));
  }
  onSBUpdateError(t, e) {
    var i;
    const s = new Error(`${t} SourceBuffer error. MediaSource readyState: ${(i = this.mediaSource) == null ? void 0 : i.readyState}`);
    this.error(`${s}`, e), this.hls.trigger(E.ERROR, {
      type: Y.MEDIA_ERROR,
      details: D.BUFFER_APPENDING_ERROR,
      sourceBufferName: t,
      error: s,
      fatal: !1
    });
    const r = this.currentOp(t);
    r && r.onError(s);
  }
  updateTimestampOffset(t, e, i, s, r, a) {
    const o = e - t.timestampOffset;
    Math.abs(o) >= i && (this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${a})`), t.timestampOffset = e);
  }
  // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  removeExecutor(t, e, i) {
    const {
      media: s,
      mediaSource: r
    } = this, a = this.tracks[t], o = a?.buffer;
    if (!s || !r || !o) {
      this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`), this.shiftAndExecuteNext(t);
      return;
    }
    const u = B(s.duration) ? s.duration : 1 / 0, l = B(r.duration) ? r.duration : 1 / 0, d = Math.max(0, e), h = Math.min(i, u, l);
    h > d && (!a.ending || a.ended) ? (a.ended = !1, this.log(`Removing [${d},${h}] from the ${t} SourceBuffer`), o.remove(d, h)) : this.shiftAndExecuteNext(t);
  }
  // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  appendExecutor(t, e) {
    const i = this.tracks[e], s = i?.buffer;
    if (!s)
      throw new Fn(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);
    i.ending = !1, i.ended = !1, s.appendBuffer(t);
  }
  blockUntilOpen(t) {
    if (this.isUpdating() || this.isQueued())
      this.blockBuffers(t).catch((e) => {
        this.warn(`SourceBuffer blocked callback ${e}`), this.stepOperationQueue(this.sourceBufferTypes);
      });
    else
      try {
        t();
      } catch (e) {
        this.warn(`Callback run without blocking ${this.operationQueue} ${e}`);
      }
  }
  isUpdating() {
    return this.sourceBuffers.some(([t, e]) => t && e.updating);
  }
  isQueued() {
    return this.sourceBuffers.some(([t]) => t && !!this.currentOp(t));
  }
  isPending(t) {
    return !!t && !t.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(t, e = this.sourceBufferTypes) {
    if (!e.length)
      return this.log("Blocking operation requested, but no SourceBuffers exist"), Promise.resolve().then(t);
    const {
      operationQueue: i
    } = this, s = e.map((a) => this.appendBlocker(a));
    return e.length > 1 && !!this.blockedAudioAppend && this.unblockAudio(), Promise.all(s).then((a) => {
      i === this.operationQueue && (t(), this.stepOperationQueue(this.sourceBufferTypes));
    });
  }
  stepOperationQueue(t) {
    t.forEach((e) => {
      var i;
      const s = (i = this.tracks[e]) == null ? void 0 : i.buffer;
      !s || s.updating || this.shiftAndExecuteNext(e);
    });
  }
  append(t, e, i) {
    this.operationQueue && this.operationQueue.append(t, e, i);
  }
  appendBlocker(t) {
    if (this.operationQueue)
      return this.operationQueue.appendBlocker(t);
  }
  currentOp(t) {
    return this.operationQueue ? this.operationQueue.current(t) : null;
  }
  executeNext(t) {
    t && this.operationQueue && this.operationQueue.executeNext(t);
  }
  shiftAndExecuteNext(t) {
    this.operationQueue && this.operationQueue.shiftAndExecuteNext(t);
  }
  get pendingTrackCount() {
    return Object.keys(this.tracks).reduce((t, e) => t + (this.isPending(this.tracks[e]) ? 1 : 0), 0);
  }
  get sourceBufferCount() {
    return this.sourceBuffers.reduce((t, [e]) => t + (e ? 1 : 0), 0);
  }
  get sourceBufferTypes() {
    return this.sourceBuffers.map(([t]) => t).filter((t) => !!t);
  }
  addBufferListener(t, e, i) {
    const s = this.tracks[t];
    if (!s)
      return;
    const r = s.buffer;
    if (!r)
      return;
    const a = i.bind(this, t);
    s.listeners.push({
      event: e,
      listener: a
    }), r.addEventListener(e, a);
  }
  removeBufferListeners(t) {
    const e = this.tracks[t];
    if (!e)
      return;
    const i = e.buffer;
    i && (e.listeners.forEach((s) => {
      i.removeEventListener(s.event, s.listener);
    }), e.listeners.length = 0);
  }
}
function Wi(n) {
  const t = n.querySelectorAll("source");
  [].slice.call(t).forEach((e) => {
    n.removeChild(e);
  });
}
function Nn(n, t) {
  const e = self.document.createElement("source");
  e.type = "video/mp4", e.src = t, n.appendChild(e);
}
function De(n) {
  return n === "audio" ? 1 : 0;
}
class ei {
  constructor(t) {
    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 = t, this.autoLevelCapping = Number.POSITIVE_INFINITY, this.firstLevel = -1, this.media = null, this.restrictedLevels = [], this.timer = void 0, this.clientRect = null, this.registerListeners();
  }
  setStreamController(t) {
    this.streamController = t;
  }
  destroy() {
    this.hls && this.unregisterListener(), this.timer && this.stopCapping(), this.media = null, this.clientRect = null, this.hls = this.streamController = null;
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t.on(E.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this), t.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.on(E.MANIFEST_PARSED, this.onManifestParsed, this), t.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.on(E.BUFFER_CODECS, this.onBufferCodecs, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListener() {
    const {
      hls: t
    } = this;
    t.off(E.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this), t.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.off(E.MANIFEST_PARSED, this.onManifestParsed, this), t.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.off(E.BUFFER_CODECS, this.onBufferCodecs, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  onFpsDropLevelCapping(t, e) {
    const i = this.hls.levels[e.droppedLevel];
    this.isLevelAllowed(i) && this.restrictedLevels.push({
      bitrate: i.bitrate,
      height: i.height,
      width: i.width
    });
  }
  onMediaAttaching(t, e) {
    this.media = e.media instanceof HTMLVideoElement ? e.media : null, this.clientRect = null, this.timer && this.hls.levels.length && this.detectPlayerSize();
  }
  onManifestParsed(t, e) {
    const i = this.hls;
    this.restrictedLevels = [], this.firstLevel = e.firstLevel, i.config.capLevelToPlayerSize && e.video && this.startCapping();
  }
  onLevelsUpdated(t, e) {
    this.timer && B(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(t, e) {
    this.hls.config.capLevelToPlayerSize && e.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 t = this.hls.levels;
      if (t.length) {
        const e = this.hls, i = this.getMaxLevel(t.length - 1);
        i !== this.autoLevelCapping && e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`), e.autoLevelCapping = i, e.autoLevelEnabled && e.autoLevelCapping > this.autoLevelCapping && this.streamController && this.streamController.nextLevelSwitch(), this.autoLevelCapping = e.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(t) {
    const e = this.hls.levels;
    if (!e.length)
      return -1;
    const i = e.filter((s, r) => this.isLevelAllowed(s) && r <= t);
    return this.clientRect = null, ei.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 t = this.media, e = {
      width: 0,
      height: 0
    };
    if (t) {
      const i = t.getBoundingClientRect();
      e.width = i.width, e.height = i.height, !e.width && !e.height && (e.width = i.right - i.left || t.width || 0, e.height = i.bottom - i.top || t.height || 0);
    }
    return this.clientRect = e, e;
  }
  get mediaWidth() {
    return this.getDimensions().width * this.contentScaleFactor;
  }
  get mediaHeight() {
    return this.getDimensions().height * this.contentScaleFactor;
  }
  get contentScaleFactor() {
    let t = 1;
    if (!this.hls.config.ignoreDevicePixelRatio)
      try {
        t = self.devicePixelRatio;
      } catch {
      }
    return Math.min(t, this.hls.config.maxDevicePixelRatio);
  }
  isLevelAllowed(t) {
    return !this.restrictedLevels.some((i) => t.bitrate === i.bitrate && t.width === i.width && t.height === i.height);
  }
  static getMaxLevelByMediaSize(t, e, i) {
    if (!(t != null && t.length))
      return -1;
    const s = (o, u) => u ? o.width !== u.width || o.height !== u.height : !0;
    let r = t.length - 1;
    const a = Math.max(e, i);
    for (let o = 0; o < t.length; o += 1) {
      const u = t[o];
      if ((u.width >= a || u.height >= a) && s(u, t[o + 1])) {
        r = o;
        break;
      }
    }
    return r;
  }
}
const Bn = 3e5;
class $n extends Rt {
  constructor(t) {
    super("content-steering", t.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 = t, this.registerListeners();
  }
  registerListeners() {
    const t = this.hls;
    t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.on(E.MANIFEST_PARSED, this.onManifestParsed, this), t.on(E.ERROR, this.onError, this);
  }
  unregisterListeners() {
    const t = this.hls;
    t && (t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.off(E.MANIFEST_PARSED, this.onManifestParsed, this), t.off(E.ERROR, this.onError, this));
  }
  pathways() {
    return (this.levels || []).reduce((t, e) => (t.indexOf(e.pathwayId) === -1 && t.push(e.pathwayId), t), []);
  }
  get pathwayPriority() {
    return this._pathwayPriority;
  }
  set pathwayPriority(t) {
    this.updatePathwayPriority(t);
  }
  startLoad() {
    if (this.started = !0, this.clearTimeout(), this.enabled && this.uri) {
      if (this.updated) {
        const t = this.timeToLoad * 1e3 - (performance.now() - this.updated);
        if (t > 0) {
          this.scheduleRefresh(this.uri, t);
          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(t) {
    const e = this.levels;
    e && (this.levels = e.filter((i) => i !== t));
  }
  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(t, e) {
    const {
      contentSteering: i
    } = e;
    i !== null && (this.pathwayId = i.pathwayId, this.uri = i.uri, this.started && this.startLoad());
  }
  onManifestParsed(t, e) {
    this.audioTracks = e.audioTracks, this.subtitleTracks = e.subtitleTracks;
  }
  onError(t, e) {
    const {
      errorAction: i
    } = e;
    if (i?.action === at.SendAlternateToPenaltyBox && i.flags === ut.MoveAllAlternatesMatchingHost) {
      const s = this.levels;
      let r = this._pathwayPriority, a = this.pathwayId;
      if (e.context) {
        const {
          groupId: o,
          pathwayId: u,
          type: l
        } = e.context;
        o && s ? a = this.getPathwayForGroupId(o, l, a) : u && (a = u);
      }
      a in this.penalizedPathways || (this.penalizedPathways[a] = performance.now()), !r && s && (r = this.pathways()), r && r.length > 1 && (this.updatePathwayPriority(r), i.resolved = this.pathwayId !== a), e.details === D.BUFFER_APPEND_ERROR && !e.fatal ? i.resolved = !0 : i.resolved || this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${a} levels: ${s && s.length} priorities: ${ot(r)} penalized: ${ot(this.penalizedPathways)}`);
    }
  }
  filterParsedLevels(t) {
    this.levels = t;
    let e = this.getLevelsForPathway(this.pathwayId);
    if (e.length === 0) {
      const i = t[0].pathwayId;
      this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`), e = this.getLevelsForPathway(i), this.pathwayId = i;
    }
    return e.length !== t.length && this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`), e;
  }
  getLevelsForPathway(t) {
    return this.levels === null ? [] : this.levels.filter((e) => t === e.pathwayId);
  }
  updatePathwayPriority(t) {
    this._pathwayPriority = t;
    let e;
    const i = this.penalizedPathways, s = performance.now();
    Object.keys(i).forEach((r) => {
      s - i[r] > Bn && delete i[r];
    });
    for (let r = 0; r < t.length; r++) {
      const a = t[r];
      if (a in i)
        continue;
      if (a === this.pathwayId)
        return;
      const o = this.hls.nextLoadLevel, u = this.hls.levels[o];
      if (e = this.getLevelsForPathway(a), e.length > 0) {
        this.log(`Setting Pathway to "${a}"`), this.pathwayId = a, ws(e), this.hls.trigger(E.LEVELS_UPDATED, {
          levels: e
        });
        const l = this.hls.levels[o];
        u && l && this.levels && (l.attrs["STABLE-VARIANT-ID"] !== u.attrs["STABLE-VARIANT-ID"] && l.bitrate !== u.bitrate && this.log(`Unstable Pathways change from bitrate ${u.bitrate} to ${l.bitrate}`), this.hls.nextLoadLevel = o);
        break;
      }
    }
  }
  getPathwayForGroupId(t, e, i) {
    const s = this.getLevelsForPathway(i).concat(this.levels || []);
    for (let r = 0; r < s.length; r++)
      if (e === X.AUDIO_TRACK && s[r].hasAudioGroup(t) || e === X.SUBTITLE_TRACK && s[r].hasSubtitleGroup(t))
        return s[r].pathwayId;
    return i;
  }
  clonePathways(t) {
    const e = this.levels;
    if (!e)
      return;
    const i = {}, s = {};
    t.forEach((r) => {
      const {
        ID: a,
        "BASE-ID": o,
        "URI-REPLACEMENT": u
      } = r;
      if (e.some((d) => d.pathwayId === a))
        return;
      const l = this.getLevelsForPathway(o).map((d) => {
        const h = new it(d.attrs);
        h["PATHWAY-ID"] = a;
        const c = h.AUDIO && `${h.AUDIO}_clone_${a}`, f = h.SUBTITLES && `${h.SUBTITLES}_clone_${a}`;
        c && (i[h.AUDIO] = c, h.AUDIO = c), f && (s[h.SUBTITLES] = f, h.SUBTITLES = f);
        const g = $s(d.uri, h["STABLE-VARIANT-ID"], "PER-VARIANT-URIS", u), p = new Ts({
          attrs: h,
          audioCodec: d.audioCodec,
          bitrate: d.bitrate,
          height: d.height,
          name: d.name,
          url: g,
          videoCodec: d.videoCodec,
          width: d.width
        });
        if (d.audioGroups)
          for (let m = 1; m < d.audioGroups.length; m++)
            p.addGroupId("audio", `${d.audioGroups[m]}_clone_${a}`);
        if (d.subtitleGroups)
          for (let m = 1; m < d.subtitleGroups.length; m++)
            p.addGroupId("text", `${d.subtitleGroups[m]}_clone_${a}`);
        return p;
      });
      e.push(...l), Yi(this.audioTracks, i, u, a), Yi(this.subtitleTracks, s, u, a);
    });
  }
  loadSteeringManifest(t) {
    const e = this.hls.config, i = e.loader;
    this.loader && this.loader.destroy(), this.loader = new i(e);
    let s;
    try {
      s = new self.URL(t);
    } catch {
      this.enabled = !1, this.log(`Failed to parse Steering Manifest URI: ${t}`);
      return;
    }
    if (s.protocol !== "data:") {
      const d = (this.hls.bandwidthEstimate || e.abrEwmaDefaultEstimate) | 0;
      s.searchParams.set("_HLS_pathway", this.pathwayId), s.searchParams.set("_HLS_throughput", "" + d);
    }
    const r = {
      responseType: "json",
      url: s.href
    }, a = e.steeringManifestLoadPolicy.default, o = a.errorRetry || a.timeoutRetry || {}, u = {
      loadPolicy: a,
      timeout: a.maxLoadTimeMs,
      maxRetry: o.maxNumRetry || 0,
      retryDelay: o.retryDelayMs || 0,
      maxRetryDelay: o.maxRetryDelayMs || 0
    }, l = {
      onSuccess: (d, h, c, f) => {
        this.log(`Loaded steering manifest: "${s}"`);
        const g = d.data;
        if (g?.VERSION !== 1) {
          this.log(`Steering VERSION ${g.VERSION} not supported!`);
          return;
        }
        this.updated = performance.now(), this.timeToLoad = g.TTL;
        const {
          "RELOAD-URI": p,
          "PATHWAY-CLONES": m,
          "PATHWAY-PRIORITY": y
        } = g;
        if (p)
          try {
            this.uri = new self.URL(p, s).href;
          } catch {
            this.enabled = !1, this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);
            return;
          }
        this.scheduleRefresh(this.uri || c.url), m && this.clonePathways(m);
        const T = {
          steeringManifest: g,
          url: s.toString()
        };
        this.hls.trigger(E.STEERING_MANIFEST_LOADED, T), y && this.updatePathwayPriority(y);
      },
      onError: (d, h, c, 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 g = this.timeToLoad * 1e3;
        if (d.code === 429) {
          const p = this.loader;
          if (typeof p?.getResponseHeader == "function") {
            const m = p.getResponseHeader("Retry-After");
            m && (g = parseFloat(m) * 1e3);
          }
          this.log(`Steering manifest ${h.url} rate limited`);
          return;
        }
        this.scheduleRefresh(this.uri || h.url, g);
      },
      onTimeout: (d, h, c) => {
        this.log(`Timeout loading steering manifest (${h.url})`), this.scheduleRefresh(this.uri || h.url);
      }
    };
    this.log(`Requesting steering manifest: ${s}`), this.loader.load(r, u, l);
  }
  scheduleRefresh(t, e = 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(t);
        return;
      }
      this.scheduleRefresh(t, this.timeToLoad * 1e3);
    }, e);
  }
}
function Yi(n, t, e, i) {
  n && Object.keys(t).forEach((s) => {
    const r = n.filter((a) => a.groupId === s).map((a) => {
      const o = nt({}, a);
      return o.details = void 0, o.attrs = new it(o.attrs), o.url = o.attrs.URI = $s(a.url, a.attrs["STABLE-RENDITION-ID"], "PER-RENDITION-URIS", e), o.groupId = o.attrs["GROUP-ID"] = t[s], o.attrs["PATHWAY-ID"] = i, o;
    });
    n.push(...r);
  });
}
function $s(n, t, e, i) {
  const {
    HOST: s,
    PARAMS: r,
    [e]: a
  } = i;
  let o;
  t && (o = a?.[t], o && (n = o));
  const u = new self.URL(n);
  return s && !o && (u.host = s), r && Object.keys(r).sort().forEach((l) => {
    l && u.searchParams.set(l, r[l]);
  }), u.href;
}
class Un {
  constructor(t) {
    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 = t, this.registerListeners();
  }
  setStreamController(t) {
    this.streamController = t;
  }
  registerListeners() {
    this.hls.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), this.hls.on(E.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  unregisterListeners() {
    this.hls.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), this.hls.off(E.MEDIA_DETACHING, this.onMediaDetaching, this);
  }
  destroy() {
    this.timer && clearInterval(this.timer), this.unregisterListeners(), this.isVideoPlaybackQualityAvailable = !1, this.media = null;
  }
  onMediaAttaching(t, e) {
    const i = this.hls.config;
    if (i.capLevelOnFPSDrop) {
      const s = e.media instanceof self.HTMLVideoElement ? e.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(t, e, i) {
    const s = performance.now();
    if (e) {
      if (this.lastTime) {
        const r = s - this.lastTime, a = i - this.lastDroppedFrames, o = e - this.lastDecodedFrames, u = 1e3 * a / r, l = this.hls;
        if (l.trigger(E.FPS_DROP, {
          currentDropped: a,
          currentDecoded: o,
          totalDroppedFrames: i
        }), u > 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(E.FPS_DROP_LEVEL_CAPPING, {
            level: d,
            droppedLevel: l.currentLevel
          }), l.autoLevelCapping = d, this.streamController.nextLevelSwitch());
        }
      }
      this.lastTime = s, this.lastDroppedFrames = i, this.lastDecodedFrames = e;
    }
  }
  checkFPSInterval() {
    const t = this.media;
    if (t)
      if (this.isVideoPlaybackQualityAvailable) {
        const e = t.getVideoPlaybackQuality();
        this.checkFPS(t, e.totalVideoFrames, e.droppedVideoFrames);
      } else
        this.checkFPS(t, t.webkitDecodedFrameCount, t.webkitDroppedFrameCount);
  }
}
function Gn() {
  try {
    return crypto.randomUUID();
  } catch {
    try {
      const t = URL.createObjectURL(new Blob()), e = t.toString();
      return URL.revokeObjectURL(t), e.slice(e.lastIndexOf("/") + 1);
    } catch {
      let e = (/* @__PURE__ */ new Date()).getTime();
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s) => {
        const r = (e + Math.random() * 16) % 16 | 0;
        return e = Math.floor(e / 16), (s == "x" ? r : r & 3 | 8).toString(16);
      });
    }
  }
}
var Ce = { exports: {} }, ji;
function Vn() {
  return ji || (ji = 1, (function(n) {
    var t = Object.prototype.hasOwnProperty, e = "~";
    function i() {
    }
    Object.create && (i.prototype = /* @__PURE__ */ Object.create(null), new i().__proto__ || (e = !1));
    function s(u, l, d) {
      this.fn = u, this.context = l, this.once = d || !1;
    }
    function r(u, l, d, h, c) {
      if (typeof d != "function")
        throw new TypeError("The listener must be a function");
      var f = new s(d, h || u, c), g = e ? e + l : l;
      return u._events[g] ? u._events[g].fn ? u._events[g] = [u._events[g], f] : u._events[g].push(f) : (u._events[g] = f, u._eventsCount++), u;
    }
    function a(u, l) {
      --u._eventsCount === 0 ? u._events = new i() : delete u._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)
        t.call(d, h) && l.push(e ? h.slice(1) : h);
      return Object.getOwnPropertySymbols ? l.concat(Object.getOwnPropertySymbols(d)) : l;
    }, o.prototype.listeners = function(l) {
      var d = e ? e + l : l, h = this._events[d];
      if (!h) return [];
      if (h.fn) return [h.fn];
      for (var c = 0, f = h.length, g = new Array(f); c < f; c++)
        g[c] = h[c].fn;
      return g;
    }, o.prototype.listenerCount = function(l) {
      var d = e ? e + l : l, h = this._events[d];
      return h ? h.fn ? 1 : h.length : 0;
    }, o.prototype.emit = function(l, d, h, c, f, g) {
      var p = e ? e + l : l;
      if (!this._events[p]) return !1;
      var m = this._events[p], y = arguments.length, T, v;
      if (m.fn) {
        switch (m.once && this.removeListener(l, m.fn, void 0, !0), y) {
          case 1:
            return m.fn.call(m.context), !0;
          case 2:
            return m.fn.call(m.context, d), !0;
          case 3:
            return m.fn.call(m.context, d, h), !0;
          case 4:
            return m.fn.call(m.context, d, h, c), !0;
          case 5:
            return m.fn.call(m.context, d, h, c, f), !0;
          case 6:
            return m.fn.call(m.context, d, h, c, f, g), !0;
        }
        for (v = 1, T = new Array(y - 1); v < y; v++)
          T[v - 1] = arguments[v];
        m.fn.apply(m.context, T);
      } else {
        var x = m.length, A;
        for (v = 0; v < x; v++)
          switch (m[v].once && this.removeListener(l, m[v].fn, void 0, !0), y) {
            case 1:
              m[v].fn.call(m[v].context);
              break;
            case 2:
              m[v].fn.call(m[v].context, d);
              break;
            case 3:
              m[v].fn.call(m[v].context, d, h);
              break;
            case 4:
              m[v].fn.call(m[v].context, d, h, c);
              break;
            default:
              if (!T) for (A = 1, T = new Array(y - 1); A < y; A++)
                T[A - 1] = arguments[A];
              m[v].fn.apply(m[v].context, T);
          }
      }
      return !0;
    }, o.prototype.on = function(l, d, h) {
      return r(this, l, d, h, !1);
    }, o.prototype.once = function(l, d, h) {
      return r(this, l, d, h, !0);
    }, o.prototype.removeListener = function(l, d, h, c) {
      var f = e ? e + l : l;
      if (!this._events[f]) return this;
      if (!d)
        return a(this, f), this;
      var g = this._events[f];
      if (g.fn)
        g.fn === d && (!c || g.once) && (!h || g.context === h) && a(this, f);
      else {
        for (var p = 0, m = [], y = g.length; p < y; p++)
          (g[p].fn !== d || c && !g[p].once || h && g[p].context !== h) && m.push(g[p]);
        m.length ? this._events[f] = m.length === 1 ? m[0] : m : a(this, f);
      }
      return this;
    }, o.prototype.removeAllListeners = function(l) {
      var d;
      return l ? (d = e ? e + 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 = e, o.EventEmitter = o, n.exports = o;
  })(Ce)), Ce.exports;
}
var Hn = Vn(), Us = /* @__PURE__ */ ls(Hn);
class Kn {
  constructor() {
    this.chunks = [], this.dataLength = 0;
  }
  push(t) {
    this.chunks.push(t), this.dataLength += t.length;
  }
  flush() {
    const {
      chunks: t,
      dataLength: e
    } = this;
    let i;
    if (t.length)
      t.length === 1 ? i = t[0] : i = Wn(t, e);
    else return new Uint8Array(0);
    return this.reset(), i;
  }
  reset() {
    this.chunks.length = 0, this.dataLength = 0;
  }
}
function Wn(n, t) {
  const e = new Uint8Array(t);
  let i = 0;
  for (let s = 0; s < n.length; s++) {
    const r = n[s];
    e.set(r, i), i += r.length;
  }
  return e;
}
function Gs(n, t) {
  return t + 10 <= n.length && n[t] === 51 && n[t + 1] === 68 && n[t + 2] === 73 && n[t + 3] < 255 && n[t + 4] < 255 && n[t + 6] < 128 && n[t + 7] < 128 && n[t + 8] < 128 && n[t + 9] < 128;
}
function ii(n, t) {
  return t + 10 <= n.length && n[t] === 73 && n[t + 1] === 68 && n[t + 2] === 51 && n[t + 3] < 255 && n[t + 4] < 255 && n[t + 6] < 128 && n[t + 7] < 128 && n[t + 8] < 128 && n[t + 9] < 128;
}
function Te(n, t) {
  let e = 0;
  return e = (n[t] & 127) << 21, e |= (n[t + 1] & 127) << 14, e |= (n[t + 2] & 127) << 7, e |= n[t + 3] & 127, e;
}
function pe(n, t) {
  const e = t;
  let i = 0;
  for (; ii(n, t); ) {
    i += 10;
    const s = Te(n, t + 6);
    i += s, Gs(n, t + 10) && (i += 10), t += i;
  }
  if (i > 0)
    return n.subarray(e, e + i);
}
function Yn(n, t, e, i) {
  const s = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], r = t[e + 2], a = r >> 2 & 15;
  if (a > 12) {
    const f = new Error(`invalid ADTS sampling index:${a}`);
    n.emit(E.ERROR, E.ERROR, {
      type: Y.MEDIA_ERROR,
      details: D.FRAG_PARSING_ERROR,
      fatal: !0,
      error: f,
      reason: f.message
    });
    return;
  }
  const o = (r >> 6 & 3) + 1, u = t[e + 3] >> 6 & 3 | (r & 1) << 2, l = "mp4a.40." + o, d = s[a];
  let h = a;
  (o === 5 || o === 29) && (h -= 3);
  const c = [o << 3 | (h & 14) >> 1, (h & 1) << 7 | u << 3];
  return J.log(`manifest codec:${i}, parsed codec:${l}, channels:${u}, rate:${d} (ADTS object type:${o} sampling index:${a})`), {
    config: c,
    samplerate: d,
    channelCount: u,
    codec: l,
    parsedCodec: l,
    manifestCodec: i
  };
}
function Vs(n, t) {
  return n[t] === 255 && (n[t + 1] & 246) === 240;
}
function Hs(n, t) {
  return n[t + 1] & 1 ? 7 : 9;
}
function si(n, t) {
  return (n[t + 3] & 3) << 11 | n[t + 4] << 3 | (n[t + 5] & 224) >>> 5;
}
function jn(n, t) {
  return t + 5 < n.length;
}
function Ee(n, t) {
  return t + 1 < n.length && Vs(n, t);
}
function qn(n, t) {
  return jn(n, t) && Vs(n, t) && si(n, t) <= n.length - t;
}
function zn(n, t) {
  if (Ee(n, t)) {
    const e = Hs(n, t);
    if (t + e >= n.length)
      return !1;
    const i = si(n, t);
    if (i <= e)
      return !1;
    const s = t + i;
    return s === n.length || Ee(n, s);
  }
  return !1;
}
function Ks(n, t, e, i, s) {
  if (!n.samplerate) {
    const r = Yn(t, e, i, s);
    if (!r)
      return;
    nt(n, r);
  }
}
function Ws(n) {
  return 1024 * 9e4 / n;
}
function Xn(n, t) {
  const e = Hs(n, t);
  if (t + e <= n.length) {
    const i = si(n, t) - e;
    if (i > 0)
      return {
        headerLength: e,
        frameLength: i
      };
  }
}
function Ys(n, t, e, i, s) {
  const r = Ws(n.samplerate), a = i + s * r, o = Xn(t, e);
  let u;
  if (o) {
    const {
      frameLength: h,
      headerLength: c
    } = o, f = c + h, g = Math.max(0, e + f - t.length);
    g ? (u = new Uint8Array(f - c), u.set(t.subarray(e + c, t.length), 0)) : u = t.subarray(e + c, e + f);
    const p = {
      unit: u,
      pts: a
    };
    return g || n.samples.push(p), {
      sample: p,
      length: f,
      missing: g
    };
  }
  const l = t.length - e;
  return u = new Uint8Array(l), u.set(t.subarray(e, t.length), 0), {
    sample: {
      unit: u,
      pts: a
    },
    length: l,
    missing: -1
  };
}
function Qn(n, t) {
  return ii(n, t) && Te(n, t + 6) + 10 <= n.length - t;
}
function Zn(n) {
  return n instanceof ArrayBuffer ? n : n.byteOffset == 0 && n.byteLength == n.buffer.byteLength ? n.buffer : new Uint8Array(n).buffer;
}
function _e(n, t = 0, e = 1 / 0) {
  return Jn(n, t, e, Uint8Array);
}
function Jn(n, t, e, i) {
  const s = ta(n);
  let r = 1;
  "BYTES_PER_ELEMENT" in i && (r = i.BYTES_PER_ELEMENT);
  const a = ea(n) ? n.byteOffset : 0, o = (a + n.byteLength) / r, u = (a + t) / r, l = Math.floor(Math.max(0, Math.min(u, o))), d = Math.floor(Math.min(l + Math.max(e, 0), o));
  return new i(s, l, d - l);
}
function ta(n) {
  return n instanceof ArrayBuffer ? n : n.buffer;
}
function ea(n) {
  return n && n.buffer instanceof ArrayBuffer && n.byteLength !== void 0 && n.byteOffset !== void 0;
}
function ia(n) {
  const t = {
    key: n.type,
    description: "",
    data: "",
    mimeType: null,
    pictureType: null
  }, e = 3;
  if (n.size < 2)
    return;
  if (n.data[0] !== e) {
    console.log("Ignore frame with unrecognized character encoding");
    return;
  }
  const i = n.data.subarray(1).indexOf(0);
  if (i === -1)
    return;
  const s = gt(_e(n.data, 1, i)), r = n.data[2 + i], a = n.data.subarray(3 + i).indexOf(0);
  if (a === -1)
    return;
  const o = gt(_e(n.data, 3 + i, a));
  let u;
  return s === "-->" ? u = gt(_e(n.data, 4 + i + a)) : u = Zn(n.data.subarray(4 + i + a)), t.mimeType = s, t.pictureType = r, t.description = o, t.data = u, t;
}
function sa(n) {
  if (n.size < 2)
    return;
  const t = gt(n.data, !0), e = new Uint8Array(n.data.subarray(t.length + 1));
  return {
    key: n.type,
    info: t,
    data: e.buffer
  };
}
function ra(n) {
  if (n.size < 2)
    return;
  if (n.type === "TXXX") {
    let e = 1;
    const i = gt(n.data.subarray(e), !0);
    e += i.length + 1;
    const s = gt(n.data.subarray(e));
    return {
      key: n.type,
      info: i,
      data: s
    };
  }
  const t = gt(n.data.subarray(1));
  return {
    key: n.type,
    info: "",
    data: t
  };
}
function na(n) {
  if (n.type === "WXXX") {
    if (n.size < 2)
      return;
    let e = 1;
    const i = gt(n.data.subarray(e), !0);
    e += i.length + 1;
    const s = gt(n.data.subarray(e));
    return {
      key: n.type,
      info: i,
      data: s
    };
  }
  const t = gt(n.data);
  return {
    key: n.type,
    info: "",
    data: t
  };
}
function aa(n) {
  return n.type === "PRIV" ? sa(n) : n.type[0] === "W" ? na(n) : n.type === "APIC" ? ia(n) : ra(n);
}
function oa(n) {
  const t = String.fromCharCode(n[0], n[1], n[2], n[3]), e = Te(n, 4), i = 10;
  return {
    type: t,
    size: e,
    data: n.subarray(i, i + e)
  };
}
const se = 10, la = 10;
function js(n) {
  let t = 0;
  const e = [];
  for (; ii(n, t); ) {
    const i = Te(n, t + 6);
    n[t + 5] >> 6 & 1 && (t += se), t += se;
    const s = t + i;
    for (; t + la < s; ) {
      const r = oa(n.subarray(t)), a = aa(r);
      a && e.push(a), t += r.size + se;
    }
    Gs(n, t) && (t += se);
  }
  return e;
}
function qs(n) {
  return n && n.key === "PRIV" && n.info === "com.apple.streaming.transportStreamTimestamp";
}
function ua(n) {
  if (n.data.byteLength === 8) {
    const t = new Uint8Array(n.data), e = t[3] & 1;
    let i = (t[4] << 23) + (t[5] << 15) + (t[6] << 7) + t[7];
    return i /= 45, e && (i += 4772185884e-2), Math.round(i);
  }
}
function zs(n) {
  const t = js(n);
  for (let e = 0; e < t.length; e++) {
    const i = t[e];
    if (qs(i))
      return ua(i);
  }
}
let dt = /* @__PURE__ */ (function(n) {
  return n.audioId3 = "org.id3", n.dateRange = "com.apple.quicktime.HLS", n.emsg = "https://aomedia.org/emsg/ID3", n.misbklv = "urn:misb:KLV:bin:1910.1", n;
})({});
function yt(n = "", t = 9e4) {
  return {
    type: n,
    id: -1,
    pid: -1,
    inputTimeScale: t,
    sequenceNumber: -1,
    samples: [],
    dropped: 0
  };
}
class Xs {
  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(t, e, i, s) {
    this._id3Track = {
      type: "id3",
      id: 3,
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0
    };
  }
  resetTimeStamp(t) {
    this.initPTS = t, this.resetContiguity();
  }
  resetContiguity() {
    this.basePTS = null, this.lastPTS = null, this.frameIndex = 0;
  }
  canParse(t, e) {
    return !1;
  }
  appendFrame(t, e, i) {
  }
  // feed incoming data to the front of the parsing pipeline
  demux(t, e) {
    this.cachedData && (t = mt(this.cachedData, t), this.cachedData = null);
    let i = pe(t, 0), s = i ? i.length : 0, r;
    const a = this._audioTrack, o = this._id3Track, u = i ? zs(i) : void 0, l = t.length;
    for ((this.basePTS === null || this.frameIndex === 0 && B(u)) && (this.basePTS = da(u, e, 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: dt.audioId3,
      duration: Number.POSITIVE_INFINITY
    }); s < l; ) {
      if (this.canParse(t, s)) {
        const d = this.appendFrame(a, t, s);
        d ? (this.frameIndex++, this.lastPTS = d.sample.pts, s += d.length, r = s) : s = l;
      } else Qn(t, s) ? (i = pe(t, s), o.samples.push({
        pts: this.lastPTS,
        dts: this.lastPTS,
        data: i,
        type: dt.audioId3,
        duration: Number.POSITIVE_INFINITY
      }), s += i.length, r = s) : s++;
      if (s === l && r !== l) {
        const d = t.slice(r);
        this.cachedData ? this.cachedData = mt(this.cachedData, d) : this.cachedData = d;
      }
    }
    return {
      audioTrack: a,
      videoTrack: yt(),
      id3Track: o,
      textTrack: yt()
    };
  }
  demuxSampleAes(t, e, i) {
    return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  }
  flush(t) {
    const e = this.cachedData;
    return e && (this.cachedData = null, this.demux(e, 0)), {
      audioTrack: this._audioTrack,
      videoTrack: yt(),
      id3Track: this._id3Track,
      textTrack: yt()
    };
  }
  destroy() {
    this.cachedData = null, this._audioTrack = this._id3Track = void 0;
  }
}
const da = (n, t, e) => {
  if (B(n))
    return n * 90;
  const i = e ? e.baseTime * 9e4 / e.timescale : 0;
  return t * 9e4 + i;
};
let re = null;
const ha = [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], ca = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3], fa = [
  // 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
  ]
], ga = [
  0,
  // Reserved
  1,
  // Layer3
  1,
  // Layer2
  4
  // Layer1
];
function Qs(n, t, e, i, s) {
  if (e + 24 > t.length)
    return;
  const r = Zs(t, e);
  if (r && e + r.frameLength <= t.length) {
    const a = r.samplesPerFrame * 9e4 / r.sampleRate, o = i + s * a, u = {
      unit: t.subarray(e, e + r.frameLength),
      pts: o,
      dts: o
    };
    return n.config = [], n.channelCount = r.channelCount, n.samplerate = r.sampleRate, n.samples.push(u), {
      sample: u,
      length: r.frameLength,
      missing: 0
    };
  }
}
function Zs(n, t) {
  const e = n[t + 1] >> 3 & 3, i = n[t + 1] >> 1 & 3, s = n[t + 2] >> 4 & 15, r = n[t + 2] >> 2 & 3;
  if (e !== 1 && s !== 0 && s !== 15 && r !== 3) {
    const a = n[t + 2] >> 1 & 1, o = n[t + 3] >> 6, u = e === 3 ? 3 - i : i === 3 ? 3 : 4, l = ha[u * 14 + s - 1] * 1e3, h = ca[(e === 3 ? 0 : e === 2 ? 1 : 2) * 3 + r], c = o === 3 ? 1 : 2, f = fa[e][i], g = ga[i], p = f * 8 * g, m = Math.floor(f * l / h + a) * g;
    if (re === null) {
      const v = (navigator.userAgent || "").match(/Chrome\/(\d+)/i);
      re = v ? parseInt(v[1]) : 0;
    }
    return !!re && re <= 87 && i === 2 && l >= 224e3 && o === 0 && (n[t + 3] = n[t + 3] | 128), {
      sampleRate: h,
      channelCount: c,
      frameLength: m,
      samplesPerFrame: p
    };
  }
}
function ri(n, t) {
  return n[t] === 255 && (n[t + 1] & 224) === 224 && (n[t + 1] & 6) !== 0;
}
function Js(n, t) {
  return t + 1 < n.length && ri(n, t);
}
function ma(n, t) {
  return ri(n, t) && 4 <= n.length - t;
}
function tr(n, t) {
  if (t + 1 < n.length && ri(n, t)) {
    const i = Zs(n, t);
    let s = 4;
    i != null && i.frameLength && (s = i.frameLength);
    const r = t + s;
    return r === n.length || Js(n, r);
  }
  return !1;
}
class pa extends Xs {
  constructor(t, e) {
    super(), this.observer = void 0, this.config = void 0, this.observer = t, this.config = e;
  }
  resetInitSegment(t, e, i, s) {
    super.resetInitSegment(t, e, i, s), this._audioTrack = {
      container: "audio/adts",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "aac",
      samples: [],
      manifestCodec: e,
      duration: s,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  static probe(t, e) {
    if (!t)
      return !1;
    const i = pe(t, 0);
    let s = i?.length || 0;
    if (tr(t, s))
      return !1;
    for (let r = t.length; s < r; s++)
      if (zn(t, s))
        return e.log("ADTS sync word found !"), !0;
    return !1;
  }
  canParse(t, e) {
    return qn(t, e);
  }
  appendFrame(t, e, i) {
    Ks(t, this.observer, e, i, t.manifestCodec);
    const s = Ys(t, e, i, this.basePTS, this.frameIndex);
    if (s && s.missing === 0)
      return s;
  }
}
const Ea = (n, t) => {
  let e = 0, i = 5;
  t += i;
  const s = new Uint32Array(1), r = new Uint32Array(1), a = new Uint8Array(1);
  for (; i > 0; ) {
    a[0] = n[t];
    const o = Math.min(i, 8), u = 8 - o;
    r[0] = 4278190080 >>> 24 + u << u, s[0] = (a[0] & r[0]) >> u, e = e ? e << o | s[0] : s[0], t += 1, i -= o;
  }
  return e;
};
class va extends Xs {
  resetInitSegment(t, e, i, s) {
    super.resetInitSegment(t, e, i, s), this._audioTrack = {
      container: "audio/mpeg",
      type: "audio",
      id: 2,
      pid: -1,
      sequenceNumber: 0,
      segmentCodec: "mp3",
      samples: [],
      manifestCodec: e,
      duration: s,
      inputTimeScale: 9e4,
      dropped: 0
    };
  }
  static probe(t) {
    if (!t)
      return !1;
    const e = pe(t, 0);
    let i = e?.length || 0;
    if (e && t[i] === 11 && t[i + 1] === 119 && zs(e) !== void 0 && // check the bsid to confirm ac-3 or ec-3 (not mp3)
    Ea(t, i) <= 16)
      return !1;
    for (let s = t.length; i < s; i++)
      if (tr(t, i))
        return J.log("MPEG Audio sync word found !"), !0;
    return !1;
  }
  canParse(t, e) {
    return ma(t, e);
  }
  appendFrame(t, e, i) {
    if (this.basePTS !== null)
      return Qs(t, e, i, this.basePTS, this.frameIndex);
  }
}
const ya = /\/emsg[-/]ID3/i;
class Ta {
  constructor(t, e) {
    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 = e;
  }
  resetTimeStamp() {
  }
  resetInitSegment(t, e, i, s) {
    const r = this.videoTrack = yt("video", 1), a = this.audioTrack = yt("audio", 1), o = this.txtTrack = yt("text", 1);
    if (this.id3Track = yt("id3", 1), this.timeOffset = 0, !(t != null && t.byteLength))
      return;
    const u = ms(t);
    if (u.video) {
      const {
        id: l,
        timescale: d,
        codec: h,
        supplemental: c
      } = u.video;
      r.id = l, r.timescale = o.timescale = d, r.codec = h, r.supplemental = c;
    }
    if (u.audio) {
      const {
        id: l,
        timescale: d,
        codec: h
      } = u.audio;
      a.id = l, a.timescale = d, a.codec = h;
    }
    o.id = cs.text, r.sampleDuration = 0, r.duration = a.duration = s;
  }
  resetContiguity() {
    this.remainderData = null;
  }
  static probe(t) {
    return Ar(t);
  }
  demux(t, e) {
    this.timeOffset = e;
    let i = t;
    const s = this.videoTrack, r = this.txtTrack;
    if (this.config.progressive) {
      this.remainderData && (i = mt(this.remainderData, t));
      const o = kr(i);
      this.remainderData = o.remainder, s.samples = o.valid || new Uint8Array();
    } else
      s.samples = i;
    const a = this.extractID3Track(s, e);
    return r.samples = hi(e, s), {
      videoTrack: s,
      audioTrack: this.audioTrack,
      id3Track: a,
      textTrack: this.txtTrack
    };
  }
  flush() {
    const t = this.timeOffset, e = this.videoTrack, i = this.txtTrack;
    e.samples = this.remainderData || new Uint8Array(), this.remainderData = null;
    const s = this.extractID3Track(e, this.timeOffset);
    return i.samples = hi(t, e), {
      videoTrack: e,
      audioTrack: yt(),
      id3Track: s,
      textTrack: yt()
    };
  }
  extractID3Track(t, e) {
    const i = this.id3Track;
    if (t.samples.length) {
      const s = j(t.samples, ["emsg"]);
      s && s.forEach((r) => {
        const a = wr(r);
        if (ya.test(a.schemeIdUri)) {
          const o = qi(a, e);
          let u = a.eventDuration === 4294967295 ? Number.POSITIVE_INFINITY : a.eventDuration / a.timeScale;
          u <= 1e-3 && (u = Number.POSITIVE_INFINITY);
          const l = a.payload;
          i.samples.push({
            data: l,
            len: l.byteLength,
            dts: o,
            pts: o,
            type: dt.emsg,
            duration: u
          });
        } else if (this.config.enableEmsgKLVMetadata && a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")) {
          const o = qi(a, e);
          i.samples.push({
            data: a.payload,
            len: a.payload.byteLength,
            dts: o,
            pts: o,
            type: dt.misbklv,
            duration: Number.POSITIVE_INFINITY
          });
        }
      });
    }
    return i;
  }
  demuxSampleAes(t, e, 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 qi(n, t) {
  return B(n.presentationTime) ? n.presentationTime / n.timeScale : t + n.presentationTimeDelta / n.timeScale;
}
class xa {
  constructor(t, e, i) {
    this.keyData = void 0, this.decrypter = void 0, this.keyData = i, this.decrypter = new ti(e, {
      removePKCS7Padding: !1
    });
  }
  decryptBuffer(t) {
    return this.decrypter.decrypt(t, this.keyData.key.buffer, this.keyData.iv.buffer, Pt.cbc);
  }
  // AAC - encrypt all full 16 bytes blocks starting from offset 16
  decryptAacSample(t, e, i) {
    const s = t[e].unit;
    if (s.length <= 16)
      return;
    const r = s.subarray(16, s.length - s.length % 16), a = r.buffer.slice(r.byteOffset, r.byteOffset + r.length);
    this.decryptBuffer(a).then((o) => {
      const u = new Uint8Array(o);
      s.set(u, 16), this.decrypter.isSync() || this.decryptAacSamples(t, e + 1, i);
    }).catch(i);
  }
  decryptAacSamples(t, e, i) {
    for (; ; e++) {
      if (e >= t.length) {
        i();
        return;
      }
      if (!(t[e].unit.length < 32) && (this.decryptAacSample(t, e, i), !this.decrypter.isSync()))
        return;
    }
  }
  // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  getAvcEncryptedData(t) {
    const e = Math.floor((t.length - 48) / 160) * 16 + 16, i = new Int8Array(e);
    let s = 0;
    for (let r = 32; r < t.length - 16; r += 160, s += 16)
      i.set(t.subarray(r, r + 16), s);
    return i;
  }
  getAvcDecryptedUnit(t, e) {
    const i = new Uint8Array(e);
    let s = 0;
    for (let r = 32; r < t.length - 16; r += 160, s += 16)
      t.set(i.subarray(s, s + 16), r);
    return t;
  }
  decryptAvcSample(t, e, i, s, r) {
    const a = vs(r.data), o = this.getAvcEncryptedData(a);
    this.decryptBuffer(o.buffer).then((u) => {
      r.data = this.getAvcDecryptedUnit(a, u), this.decrypter.isSync() || this.decryptAvcSamples(t, e, i + 1, s);
    }).catch(s);
  }
  decryptAvcSamples(t, e, i, s) {
    if (t instanceof Uint8Array)
      throw new Error("Cannot decrypt samples of type Uint8Array");
    for (; ; e++, i = 0) {
      if (e >= t.length) {
        s();
        return;
      }
      const r = t[e].units;
      for (; !(i >= r.length); i++) {
        const a = r[i];
        if (!(a.data.length <= 48 || a.type !== 1 && a.type !== 5) && (this.decryptAvcSample(t, e, i, s, a), !this.decrypter.isSync()))
          return;
      }
    }
  }
}
class Sa {
  constructor() {
    this.VideoSample = null;
  }
  createVideoSample(t, e, i) {
    return {
      key: t,
      frame: !1,
      pts: e,
      dts: i,
      units: [],
      length: 0
    };
  }
  getLastNalUnit(t) {
    var e;
    let i = this.VideoSample, s;
    if ((!i || i.units.length === 0) && (i = t[t.length - 1]), (e = i) != null && e.units) {
      const r = i.units;
      s = r[r.length - 1];
    }
    return s;
  }
  pushAccessUnit(t, e) {
    if (t.units.length && t.frame) {
      if (t.pts === void 0) {
        const i = e.samples, s = i.length;
        if (s) {
          const r = i[s - 1];
          t.pts = r.pts, t.dts = r.dts;
        } else {
          e.dropped++;
          return;
        }
      }
      e.samples.push(t);
    }
  }
  parseNALu(t, e, i) {
    const s = e.byteLength;
    let r = t.naluState || 0;
    const a = r, o = [];
    let u = 0, l, d, h, c = -1, f = 0;
    for (r === -1 && (c = 0, f = this.getNALuType(e, 0), r = 0, u = 1); u < s; ) {
      if (l = e[u++], !r) {
        r = l ? 0 : 1;
        continue;
      }
      if (r === 1) {
        r = l ? 0 : 2;
        continue;
      }
      if (!l)
        r = 3;
      else if (l === 1) {
        if (d = u - r - 1, c >= 0) {
          const g = {
            data: e.subarray(c, d),
            type: f
          };
          o.push(g);
        } else {
          const g = this.getLastNalUnit(t.samples);
          g && (a && u <= 4 - a && g.state && (g.data = g.data.subarray(0, g.data.byteLength - a)), d > 0 && (g.data = mt(g.data, e.subarray(0, d)), g.state = 0));
        }
        u < s ? (h = this.getNALuType(e, u), c = u, f = h, r = 0) : r = -1;
      } else
        r = 0;
    }
    if (c >= 0 && r >= 0) {
      const g = {
        data: e.subarray(c, s),
        type: f,
        state: r
      };
      o.push(g);
    }
    if (o.length === 0) {
      const g = this.getLastNalUnit(t.samples);
      g && (g.data = mt(g.data, e));
    }
    return t.naluState = r, o;
  }
}
class zi {
  constructor(t) {
    this.data = void 0, this.bytesAvailable = void 0, this.word = void 0, this.bitsAvailable = void 0, this.data = t, this.bytesAvailable = t.byteLength, this.word = 0, this.bitsAvailable = 0;
  }
  // ():void
  loadWord() {
    const t = this.data, e = this.bytesAvailable, i = t.byteLength - e, s = new Uint8Array(4), r = Math.min(4, e);
    if (r === 0)
      throw new Error("no bytes available");
    s.set(t.subarray(i, i + r)), this.word = new DataView(s.buffer).getUint32(0), this.bitsAvailable = r * 8, this.bytesAvailable -= r;
  }
  // (count:int):void
  skipBits(t) {
    let e;
    t = Math.min(t, this.bytesAvailable * 8 + this.bitsAvailable), this.bitsAvailable > t ? (this.word <<= t, this.bitsAvailable -= t) : (t -= this.bitsAvailable, e = t >> 3, t -= e << 3, this.bytesAvailable -= e, this.loadWord(), this.word <<= t, this.bitsAvailable -= t);
  }
  // (size:int):uint
  readBits(t) {
    let e = Math.min(this.bitsAvailable, t);
    const i = this.word >>> 32 - e;
    if (t > 32 && J.error("Cannot read more than 32 bits at a time"), this.bitsAvailable -= e, this.bitsAvailable > 0)
      this.word <<= e;
    else if (this.bytesAvailable > 0)
      this.loadWord();
    else
      throw new Error("no bits available");
    return e = t - e, e > 0 && this.bitsAvailable ? i << e | this.readBits(e) : i;
  }
  // ():uint
  skipLZ() {
    let t;
    for (t = 0; t < this.bitsAvailable; ++t)
      if ((this.word & 2147483648 >>> t) !== 0)
        return this.word <<= t, this.bitsAvailable -= t, t;
    return this.loadWord(), t + this.skipLZ();
  }
  // ():void
  skipUEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():void
  skipEG() {
    this.skipBits(1 + this.skipLZ());
  }
  // ():uint
  readUEG() {
    const t = this.skipLZ();
    return this.readBits(t + 1) - 1;
  }
  // ():int
  readEG() {
    const t = this.readUEG();
    return 1 & t ? 1 + t >>> 1 : -1 * (t >>> 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 La extends Sa {
  parsePES(t, e, i, s) {
    const r = this.parseNALu(t, i.data, s);
    let a = this.VideoSample, o, u = !1;
    i.data = null, a && r.length && !t.audFound && (this.pushAccessUnit(a, t), a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts)), r.forEach((l) => {
      var d, h;
      switch (l.type) {
        // NDR
        case 1: {
          let p = !1;
          o = !0;
          const m = l.data;
          if (u && m.length > 4) {
            const y = this.readSliceType(m);
            (y === 2 || y === 4 || y === 7 || y === 9) && (p = !0);
          }
          if (p) {
            var c;
            (c = a) != null && c.frame && !a.key && (this.pushAccessUnit(a, t), a = this.VideoSample = null);
          }
          a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.frame = !0, a.key = p;
          break;
        }
        case 5:
          o = !0, (d = a) != null && d.frame && !a.key && (this.pushAccessUnit(a, t), a = this.VideoSample = null), a || (a = this.VideoSample = this.createVideoSample(!0, i.pts, i.dts)), a.key = !0, a.frame = !0;
          break;
        // SEI
        case 6: {
          o = !0, Es(l.data, 1, i.pts, e.samples);
          break;
        }
        case 7: {
          var f, g;
          o = !0, u = !0;
          const p = l.data, m = this.readSPS(p);
          if (!t.sps || t.width !== m.width || t.height !== m.height || ((f = t.pixelRatio) == null ? void 0 : f[0]) !== m.pixelRatio[0] || ((g = t.pixelRatio) == null ? void 0 : g[1]) !== m.pixelRatio[1]) {
            t.width = m.width, t.height = m.height, t.pixelRatio = m.pixelRatio, t.sps = [p];
            const y = p.subarray(1, 4);
            let T = "avc1.";
            for (let v = 0; v < 3; v++) {
              let x = y[v].toString(16);
              x.length < 2 && (x = "0" + x), T += x;
            }
            t.codec = T;
          }
          break;
        }
        // PPS
        case 8:
          o = !0, t.pps = [l.data];
          break;
        // AUD
        case 9:
          o = !0, t.audFound = !0, (h = a) != null && h.frame && (this.pushAccessUnit(a, t), a = null), a || (a = this.VideoSample = this.createVideoSample(!1, i.pts, i.dts));
          break;
        // Filler Data
        case 12:
          o = !0;
          break;
        default:
          o = !1;
          break;
      }
      a && o && a.units.push(l);
    }), s && a && (this.pushAccessUnit(a, t), this.VideoSample = null);
  }
  getNALuType(t, e) {
    return t[e] & 31;
  }
  readSliceType(t) {
    const e = new zi(t);
    return e.readUByte(), e.readUEG(), e.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(t, e) {
    let i = 8, s = 8, r;
    for (let a = 0; a < t; a++)
      s !== 0 && (r = e.readEG(), s = (i + r + 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(t) {
    const e = new zi(t);
    let i = 0, s = 0, r = 0, a = 0, o, u, l;
    const d = e.readUByte.bind(e), h = e.readBits.bind(e), c = e.readUEG.bind(e), f = e.readBoolean.bind(e), g = e.skipBits.bind(e), p = e.skipEG.bind(e), m = e.skipUEG.bind(e), y = this.skipScalingList.bind(this);
    d();
    const T = d();
    if (h(5), g(3), d(), m(), T === 100 || T === 110 || T === 122 || T === 244 || T === 44 || T === 83 || T === 86 || T === 118 || T === 128) {
      const R = c();
      if (R === 3 && g(1), m(), m(), g(1), f())
        for (u = R !== 3 ? 8 : 12, l = 0; l < u; l++)
          f() && (l < 6 ? y(16, e) : y(64, e));
    }
    m();
    const v = c();
    if (v === 0)
      c();
    else if (v === 1)
      for (g(1), p(), p(), o = c(), l = 0; l < o; l++)
        p();
    m(), g(1);
    const x = c(), A = c(), C = h(1);
    C === 0 && g(1), g(1), f() && (i = c(), s = c(), r = c(), a = c());
    let S = [1, 1];
    if (f() && f())
      switch (d()) {
        case 1:
          S = [1, 1];
          break;
        case 2:
          S = [12, 11];
          break;
        case 3:
          S = [10, 11];
          break;
        case 4:
          S = [16, 11];
          break;
        case 5:
          S = [40, 33];
          break;
        case 6:
          S = [24, 11];
          break;
        case 7:
          S = [20, 11];
          break;
        case 8:
          S = [32, 11];
          break;
        case 9:
          S = [80, 33];
          break;
        case 10:
          S = [18, 11];
          break;
        case 11:
          S = [15, 11];
          break;
        case 12:
          S = [64, 33];
          break;
        case 13:
          S = [160, 99];
          break;
        case 14:
          S = [4, 3];
          break;
        case 15:
          S = [3, 2];
          break;
        case 16:
          S = [2, 1];
          break;
        case 255: {
          S = [d() << 8 | d(), d() << 8 | d()];
          break;
        }
      }
    return {
      width: Math.ceil((x + 1) * 16 - i * 2 - s * 2),
      height: (2 - C) * (A + 1) * 16 - (C ? 2 : 4) * (r + a),
      pixelRatio: S
    };
  }
}
const st = 188;
class Dt {
  constructor(t, e, 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 = t, this.config = e, this.typeSupported = i, this.logger = s, this.videoParser = null;
  }
  static probe(t, e) {
    const i = Dt.syncOffset(t);
    return i > 0 && e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`), i !== -1;
  }
  static syncOffset(t) {
    const e = t.length;
    let i = Math.min(st * 5, e - st) + 1, s = 0;
    for (; s < i; ) {
      let r = !1, a = -1, o = 0;
      for (let u = s; u < e; u += st)
        if (t[u] === 71 && (e - u === st || t[u + st] === 71)) {
          if (o++, a === -1 && (a = u, a !== 0 && (i = Math.min(a + st * 99, t.length - st) + 1)), r || (r = Ke(t, u) === 0), r && o > 1 && (a === 0 && o > 2 || u + st > 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(t, e) {
    return {
      container: t === "video" || t === "audio" ? "video/mp2t" : void 0,
      type: t,
      id: cs[t],
      pid: -1,
      inputTimeScale: 9e4,
      sequenceNumber: 0,
      samples: [],
      dropped: 0,
      duration: t === "audio" ? e : 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(t, e, i, s) {
    this.pmtParsed = !1, this._pmtId = -1, this._videoTrack = Dt.createTrack("video"), this._videoTrack.duration = s, this._audioTrack = Dt.createTrack("audio", s), this._id3Track = Dt.createTrack("id3"), this._txtTrack = Dt.createTrack("text"), this._audioTrack.segmentCodec = "aac", this.videoParser = null, this.aacOverFlow = null, this.remainderData = null, this.audioCodec = e, this.videoCodec = i;
  }
  resetTimeStamp() {
  }
  resetContiguity() {
    const {
      _audioTrack: t,
      _videoTrack: e,
      _id3Track: i
    } = this;
    t && (t.pesData = null), e && (e.pesData = null), i && (i.pesData = null), this.aacOverFlow = null, this.remainderData = null;
  }
  demux(t, e, i = !1, s = !1) {
    i || (this.sampleAes = null);
    let r;
    const a = this._videoTrack, o = this._audioTrack, u = this._id3Track, l = this._txtTrack;
    let d = a.pid, h = a.pesData, c = o.pid, f = u.pid, g = o.pesData, p = u.pesData, m = null, y = this.pmtParsed, T = this._pmtId, v = t.length;
    if (this.remainderData && (t = mt(this.remainderData, t), v = t.length, this.remainderData = null), v < st && !s)
      return this.remainderData = t, {
        audioTrack: o,
        videoTrack: a,
        id3Track: u,
        textTrack: l
      };
    const x = Math.max(0, Dt.syncOffset(t));
    v -= (v - x) % st, v < t.byteLength && !s && (this.remainderData = new Uint8Array(t.buffer, v, t.buffer.byteLength - v));
    let A = 0;
    for (let S = x; S < v; S += st)
      if (t[S] === 71) {
        const R = !!(t[S + 1] & 64), b = Ke(t, S), I = (t[S + 3] & 48) >> 4;
        let _;
        if (I > 1) {
          if (_ = S + 5 + t[S + 4], _ === S + st)
            continue;
        } else
          _ = S + 4;
        switch (b) {
          case d:
            R && (h && (r = $t(h, this.logger)) && (this.readyVideoParser(a.segmentCodec), this.videoParser !== null && this.videoParser.parsePES(a, l, r, !1)), h = {
              data: [],
              size: 0
            }), h && (h.data.push(t.subarray(_, S + st)), h.size += S + st - _);
            break;
          case c:
            if (R) {
              if (g && (r = $t(g, this.logger)))
                switch (o.segmentCodec) {
                  case "aac":
                    this.parseAACPES(o, r);
                    break;
                  case "mp3":
                    this.parseMPEGPES(o, r);
                    break;
                }
              g = {
                data: [],
                size: 0
              };
            }
            g && (g.data.push(t.subarray(_, S + st)), g.size += S + st - _);
            break;
          case f:
            R && (p && (r = $t(p, this.logger)) && this.parseID3PES(u, r), p = {
              data: [],
              size: 0
            }), p && (p.data.push(t.subarray(_, S + st)), p.size += S + st - _);
            break;
          case 0:
            R && (_ += t[_] + 1), T = this._pmtId = Aa(t, _);
            break;
          case T: {
            R && (_ += t[_] + 1);
            const F = Ra(t, _, this.typeSupported, i, this.observer, this.logger);
            d = F.videoPid, d > 0 && (a.pid = d, a.segmentCodec = F.segmentVideoCodec), c = F.audioPid, c > 0 && (o.pid = c, o.segmentCodec = F.segmentAudioCodec), f = F.id3Pid, f > 0 && (u.pid = f), m !== null && !y && (this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${m}'. Backtracking to sync byte @${x} to parse all TS packets.`), m = null, S = x - 188), y = this.pmtParsed = !0;
            break;
          }
          case 17:
          case 8191:
            break;
          default:
            m = b;
            break;
        }
      } else
        A++;
    A > 0 && ve(this.observer, new Error(`Found ${A} TS packet/s that do not start with 0x47`), void 0, this.logger), a.pesData = h, o.pesData = g, u.pesData = p;
    const C = {
      audioTrack: o,
      videoTrack: a,
      id3Track: u,
      textTrack: l
    };
    return s && this.extractRemainingSamples(C), C;
  }
  flush() {
    const {
      remainderData: t
    } = this;
    this.remainderData = null;
    let e;
    return t ? e = this.demux(t, -1, !1, !0) : e = {
      videoTrack: this._videoTrack,
      audioTrack: this._audioTrack,
      id3Track: this._id3Track,
      textTrack: this._txtTrack
    }, this.extractRemainingSamples(e), this.sampleAes ? this.decrypt(e, this.sampleAes) : e;
  }
  extractRemainingSamples(t) {
    const {
      audioTrack: e,
      videoTrack: i,
      id3Track: s,
      textTrack: r
    } = t, a = i.pesData, o = e.pesData, u = s.pesData;
    let l;
    if (a && (l = $t(a, this.logger)) ? (this.readyVideoParser(i.segmentCodec), this.videoParser !== null && (this.videoParser.parsePES(i, r, l, !0), i.pesData = null)) : i.pesData = a, o && (l = $t(o, this.logger))) {
      switch (e.segmentCodec) {
        case "aac":
          this.parseAACPES(e, l);
          break;
        case "mp3":
          this.parseMPEGPES(e, l);
          break;
      }
      e.pesData = null;
    } else
      o != null && o.size && this.logger.log("last AAC PES packet truncated,might overlap between fragments"), e.pesData = o;
    u && (l = $t(u, this.logger)) ? (this.parseID3PES(s, l), s.pesData = null) : s.pesData = u;
  }
  demuxSampleAes(t, e, i) {
    const s = this.demux(t, i, !0, !this.config.progressive), r = this.sampleAes = new xa(this.observer, this.config, e);
    return this.decrypt(s, r);
  }
  readyVideoParser(t) {
    this.videoParser === null && t === "avc" && (this.videoParser = new La());
  }
  decrypt(t, e) {
    return new Promise((i) => {
      const {
        audioTrack: s,
        videoTrack: r
      } = t;
      s.samples && s.segmentCodec === "aac" ? e.decryptAacSamples(s.samples, 0, () => {
        r.samples ? e.decryptAvcSamples(r.samples, 0, 0, () => {
          i(t);
        }) : i(t);
      }) : r.samples && e.decryptAvcSamples(r.samples, 0, 0, () => {
        i(t);
      });
    });
  }
  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(t, e) {
    let i = 0;
    const s = this.aacOverFlow;
    let r = e.data;
    if (s) {
      this.aacOverFlow = null;
      const h = s.missing, c = s.sample.unit.byteLength;
      if (h === -1)
        r = mt(s.sample.unit, r);
      else {
        const f = c - h;
        s.sample.unit.set(r.subarray(0, h), f), t.samples.push(s.sample), i = s.missing;
      }
    }
    let a, o;
    for (a = i, o = r.length; a < o - 1 && !Ee(r, a); a++)
      ;
    if (a !== i) {
      let h;
      const c = a < o - 1;
      if (c ? h = `AAC PES did not start with ADTS header,offset:${a}` : h = "No ADTS header found in AAC PES", ve(this.observer, new Error(h), c, this.logger), !c)
        return;
    }
    Ks(t, this.observer, r, a, this.audioCodec);
    let u;
    if (e.pts !== void 0)
      u = e.pts;
    else if (s) {
      const h = Ws(t.samplerate);
      u = s.sample.pts + h;
    } else {
      this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");
      return;
    }
    let l = 0, d;
    for (; a < o; )
      if (d = Ys(t, r, a, u, l), a += d.length, d.missing) {
        this.aacOverFlow = d;
        break;
      } else
        for (l++; a < o - 1 && !Ee(r, a); a++)
          ;
  }
  parseMPEGPES(t, e) {
    const i = e.data, s = i.length;
    let r = 0, a = 0;
    const o = e.pts;
    if (o === void 0) {
      this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");
      return;
    }
    for (; a < s; )
      if (Js(i, a)) {
        const u = Qs(t, i, a, o, r);
        if (u)
          a += u.length, r++;
        else
          break;
      } else
        a++;
  }
  parseAC3PES(t, e) {
  }
  parseID3PES(t, e) {
    if (e.pts === void 0) {
      this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");
      return;
    }
    const i = nt({}, e, {
      type: this._videoTrack ? dt.emsg : dt.audioId3,
      duration: Number.POSITIVE_INFINITY
    });
    t.samples.push(i);
  }
}
function Ke(n, t) {
  return ((n[t + 1] & 31) << 8) + n[t + 2];
}
function Aa(n, t) {
  return (n[t + 10] & 31) << 8 | n[t + 11];
}
function Ra(n, t, e, i, s, r) {
  const a = {
    audioPid: -1,
    videoPid: -1,
    id3Pid: -1,
    segmentVideoCodec: "avc",
    segmentAudioCodec: "aac"
  }, o = (n[t + 1] & 15) << 8 | n[t + 2], u = t + 3 + o - 4, l = (n[t + 10] & 15) << 8 | n[t + 11];
  for (t += 12 + l; t < u; ) {
    const d = Ke(n, t), h = (n[t + 3] & 15) << 8 | n[t + 4];
    switch (n[t]) {
      case 207:
        if (!i) {
          Pe("ADTS AAC", r);
          break;
        }
      /* falls through */
      case 15:
        a.audioPid === -1 && (a.audioPid = d);
        break;
      // Packetized metadata (ID3)
      case 21:
        a.id3Pid === -1 && (a.id3Pid = d);
        break;
      case 219:
        if (!i) {
          Pe("H.264", r);
          break;
        }
      /* falls through */
      case 27:
        a.videoPid === -1 && (a.videoPid = d);
        break;
      // ISO/IEC 11172-3 (MPEG-1 audio)
      // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
      case 3:
      case 4:
        !e.mpeg && !e.mp3 ? r.log("MPEG audio found, not supported in this browser") : a.audioPid === -1 && (a.audioPid = d, a.segmentAudioCodec = "mp3");
        break;
      case 193:
        if (!i) {
          Pe("AC-3", r);
          break;
        }
      /* falls through */
      case 129:
        r.warn("AC-3 in M2TS support not included in build");
        break;
      case 6:
        if (a.audioPid === -1 && h > 0) {
          let c = t + 5, f = h;
          for (; f > 2; ) {
            switch (n[c]) {
              case 106:
                r.warn("AC-3 in M2TS support not included in build");
                break;
            }
            const p = n[c + 1] + 2;
            c += p, f -= p;
          }
        }
        break;
      case 194:
      // SAMPLE-AES EC3
      /* falls through */
      case 135:
        return ve(s, new Error("Unsupported EC-3 in M2TS found"), void 0, r), a;
      case 36:
        return ve(s, new Error("Unsupported HEVC in M2TS found"), void 0, r), a;
    }
    t += h + 5;
  }
  return a;
}
function ve(n, t, e, i) {
  i.warn(`parsing error: ${t.message}`), n.emit(E.ERROR, E.ERROR, {
    type: Y.MEDIA_ERROR,
    details: D.FRAG_PARSING_ERROR,
    fatal: !1,
    levelRetry: e,
    error: t,
    reason: t.message
  });
}
function Pe(n, t) {
  t.log(`${n} with AES-128-CBC encryption found in unencrypted stream`);
}
function $t(n, t) {
  let e = 0, i, s, r, a, o;
  const u = n.data;
  if (!n || n.size === 0)
    return null;
  for (; u[0].length < 19 && u.length > 1; )
    u[0] = mt(u[0], u[1]), u.splice(1, 1);
  if (i = u[0], (i[0] << 16) + (i[1] << 8) + i[2] === 1) {
    if (s = (i[4] << 8) + i[5], s && s > n.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 && (t.warn(`${Math.round((a - o) / 9e4)}s delta between PTS and DTS, align them`), a = o)) : o = a), r = i[8];
    let h = r + 9;
    if (n.size <= h)
      return null;
    n.size -= h;
    const c = new Uint8Array(n.size);
    for (let f = 0, g = u.length; f < g; f++) {
      i = u[f];
      let p = i.byteLength;
      if (h)
        if (h > p) {
          h -= p;
          continue;
        } else
          i = i.subarray(h), p -= h, h = 0;
      c.set(i, e), e += p;
    }
    return s && (s -= r + 3), {
      data: c,
      pts: a,
      dts: o,
      len: s
    };
  }
  return null;
}
class ba {
  static getSilentFrame(t, e) {
    switch (t) {
      case "mp4a.40.2":
        if (e === 1)
          return new Uint8Array([0, 200, 0, 128, 35, 128]);
        if (e === 2)
          return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]);
        if (e === 3)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]);
        if (e === 4)
          return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]);
        if (e === 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 (e === 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;
      // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
      default:
        if (e === 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 (e === 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 (e === 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 bt = Math.pow(2, 32) - 1;
class L {
  static init() {
    L.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 t;
    for (t in L.types)
      L.types.hasOwnProperty(t) && (L.types[t] = [t.charCodeAt(0), t.charCodeAt(1), t.charCodeAt(2), t.charCodeAt(3)]);
    const e = 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'
    ]);
    L.HDLR_TYPES = {
      video: e,
      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
    ]), r = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0
      // entry_count
    ]);
    L.STTS = L.STSC = L.STCO = r, L.STSZ = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      0,
      0,
      // sample_size
      0,
      0,
      0,
      0
      // sample_count
    ]), L.VMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      1,
      // flags
      0,
      0,
      // graphicsmode
      0,
      0,
      0,
      0,
      0,
      0
      // opcolor
    ]), L.SMHD = new Uint8Array([
      0,
      // version
      0,
      0,
      0,
      // flags
      0,
      0,
      // balance
      0,
      0
      // reserved
    ]), L.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]), u = new Uint8Array([0, 0, 0, 1]);
    L.FTYP = L.box(L.types.ftyp, a, u, a, o), L.DINF = L.box(L.types.dinf, L.box(L.types.dref, s));
  }
  static box(t, ...e) {
    let i = 8, s = e.length;
    const r = s;
    for (; s--; )
      i += e[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(t, 4), s = 0, i = 8; s < r; s++)
      a.set(e[s], i), i += e[s].byteLength;
    return a;
  }
  static hdlr(t) {
    return L.box(L.types.hdlr, L.HDLR_TYPES[t]);
  }
  static mdat(t) {
    return L.box(L.types.mdat, t);
  }
  static mdhd(t, e) {
    e *= t;
    const i = Math.floor(e / (bt + 1)), s = Math.floor(e % (bt + 1));
    return L.box(L.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
      t >> 24 & 255,
      t >> 16 & 255,
      t >> 8 & 255,
      t & 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(t) {
    return L.box(L.types.mdia, L.mdhd(t.timescale || 0, t.duration || 0), L.hdlr(t.type), L.minf(t));
  }
  static mfhd(t) {
    return L.box(L.types.mfhd, new Uint8Array([
      0,
      0,
      0,
      0,
      // flags
      t >> 24,
      t >> 16 & 255,
      t >> 8 & 255,
      t & 255
      // sequence_number
    ]));
  }
  static minf(t) {
    return t.type === "audio" ? L.box(L.types.minf, L.box(L.types.smhd, L.SMHD), L.DINF, L.stbl(t)) : L.box(L.types.minf, L.box(L.types.vmhd, L.VMHD), L.DINF, L.stbl(t));
  }
  static moof(t, e, i) {
    return L.box(L.types.moof, L.mfhd(t), L.traf(i, e));
  }
  static moov(t) {
    let e = t.length;
    const i = [];
    for (; e--; )
      i[e] = L.trak(t[e]);
    return L.box.apply(null, [L.types.moov, L.mvhd(t[0].timescale || 0, t[0].duration || 0)].concat(i).concat(L.mvex(t)));
  }
  static mvex(t) {
    let e = t.length;
    const i = [];
    for (; e--; )
      i[e] = L.trex(t[e]);
    return L.box.apply(null, [L.types.mvex, ...i]);
  }
  static mvhd(t, e) {
    e *= t;
    const i = Math.floor(e / (bt + 1)), s = Math.floor(e % (bt + 1)), r = 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
      t >> 24 & 255,
      t >> 16 & 255,
      t >> 8 & 255,
      t & 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 L.box(L.types.mvhd, r);
  }
  static sdtp(t) {
    const e = t.samples || [], i = new Uint8Array(4 + e.length);
    let s, r;
    for (s = 0; s < e.length; s++)
      r = e[s].flags, i[s + 4] = r.dependsOn << 4 | r.isDependedOn << 2 | r.hasRedundancy;
    return L.box(L.types.sdtp, i);
  }
  static stbl(t) {
    return L.box(L.types.stbl, L.stsd(t), L.box(L.types.stts, L.STTS), L.box(L.types.stsc, L.STSC), L.box(L.types.stsz, L.STSZ), L.box(L.types.stco, L.STCO));
  }
  static avc1(t) {
    let e = [], i = [], s, r, a;
    for (s = 0; s < t.sps.length; s++)
      r = t.sps[s], a = r.byteLength, e.push(a >>> 8 & 255), e.push(a & 255), e = e.concat(Array.prototype.slice.call(r));
    for (s = 0; s < t.pps.length; s++)
      r = t.pps[s], a = r.byteLength, i.push(a >>> 8 & 255), i.push(a & 255), i = i.concat(Array.prototype.slice.call(r));
    const o = L.box(L.types.avcC, new Uint8Array([
      1,
      // version
      e[3],
      // profile
      e[4],
      // profile compat
      e[5],
      // level
      255,
      // lengthSizeMinusOne, hard-coded to 4 bytes
      224 | t.sps.length
      // 3bit reserved (111) + numOfSequenceParameterSets
    ].concat(e).concat([
      t.pps.length
      // numOfPictureParameterSets
    ]).concat(i))), u = t.width, l = t.height, d = t.pixelRatio[0], h = t.pixelRatio[1];
    return L.box(
      L.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
        u >> 8 & 255,
        u & 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,
      L.box(L.types.btrt, new Uint8Array([
        0,
        28,
        156,
        128,
        // bufferSizeDB
        0,
        45,
        198,
        192,
        // maxBitrate
        0,
        45,
        198,
        192
      ])),
      // avgBitrate
      L.box(L.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(t) {
    const e = t.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
      ...e,
      6,
      1,
      2
      // GASpecificConfig)); // length + audio config descriptor
    ]);
  }
  static audioStsd(t) {
    const e = t.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,
      t.channelCount || 0,
      // channelcount
      0,
      16,
      // sampleSize:16bits
      0,
      0,
      0,
      0,
      // reserved2
      e >> 8 & 255,
      e & 255,
      //
      0,
      0
    ]);
  }
  static mp4a(t) {
    return L.box(L.types.mp4a, L.audioStsd(t), L.box(L.types.esds, L.esds(t)));
  }
  static mp3(t) {
    return L.box(L.types[".mp3"], L.audioStsd(t));
  }
  static ac3(t) {
    return L.box(L.types["ac-3"], L.audioStsd(t), L.box(L.types.dac3, t.config));
  }
  static stsd(t) {
    const {
      segmentCodec: e
    } = t;
    if (t.type === "audio") {
      if (e === "aac")
        return L.box(L.types.stsd, L.STSD, L.mp4a(t));
      if (e === "mp3" && t.codec === "mp3")
        return L.box(L.types.stsd, L.STSD, L.mp3(t));
    } else if (t.pps && t.sps) {
      if (e === "avc")
        return L.box(L.types.stsd, L.STSD, L.avc1(t));
    } else
      throw new Error("video track missing pps or sps");
    throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`);
  }
  static tkhd(t) {
    const e = t.id, i = (t.duration || 0) * (t.timescale || 0), s = t.width || 0, r = t.height || 0, a = Math.floor(i / (bt + 1)), o = Math.floor(i % (bt + 1));
    return L.box(L.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
      e >> 24 & 255,
      e >> 16 & 255,
      e >> 8 & 255,
      e & 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
      r >> 8 & 255,
      r & 255,
      0,
      0
      // height
    ]));
  }
  static traf(t, e) {
    const i = L.sdtp(t), s = t.id, r = Math.floor(e / (bt + 1)), a = Math.floor(e % (bt + 1));
    return L.box(
      L.types.traf,
      L.box(L.types.tfhd, new Uint8Array([
        0,
        // version 0
        0,
        0,
        0,
        // flags
        s >> 24,
        s >> 16 & 255,
        s >> 8 & 255,
        s & 255
        // track_ID
      ])),
      L.box(L.types.tfdt, new Uint8Array([
        1,
        // version 1
        0,
        0,
        0,
        // flags
        r >> 24,
        r >> 16 & 255,
        r >> 8 & 255,
        r & 255,
        a >> 24,
        a >> 16 & 255,
        a >> 8 & 255,
        a & 255
      ])),
      L.trun(t, 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(t) {
    return t.duration = t.duration || 4294967295, L.box(L.types.trak, L.tkhd(t), L.mdia(t));
  }
  static trex(t) {
    const e = t.id;
    return L.box(L.types.trex, new Uint8Array([
      0,
      // version 0
      0,
      0,
      0,
      // flags
      e >> 24,
      e >> 16 & 255,
      e >> 8 & 255,
      e & 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(t, e) {
    const i = t.samples || [], s = i.length, r = 12 + 16 * s, a = new Uint8Array(r);
    let o, u, l, d, h, c;
    for (e += 8 + r, a.set([
      t.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
      e >>> 24 & 255,
      e >>> 16 & 255,
      e >>> 8 & 255,
      e & 255
      // data_offset
    ], 0), o = 0; o < s; o++)
      u = i[o], l = u.duration, d = u.size, h = u.flags, c = u.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
        c >>> 24 & 255,
        c >>> 16 & 255,
        c >>> 8 & 255,
        c & 255
        // sample_composition_time_offset
      ], 12 + 16 * o);
    return L.box(L.types.trun, a);
  }
  static initSegment(t) {
    L.types || L.init();
    const e = L.moov(t);
    return mt(L.FTYP, e);
  }
  static hvc1(t) {
    return new Uint8Array();
  }
}
L.types = void 0;
L.HDLR_TYPES = void 0;
L.STTS = void 0;
L.STSC = void 0;
L.STCO = void 0;
L.STSZ = void 0;
L.VMHD = void 0;
L.SMHD = void 0;
L.STSD = void 0;
L.FTYP = void 0;
L.DINF = void 0;
const Ia = 9e4;
function Da(n, t, e = 1, i = !1) {
  const s = n * t * e;
  return i ? Math.round(s) : s;
}
function Kt(n, t = !1) {
  return Da(n, 1e3, 1 / Ia, t);
}
function Xi(n) {
  const {
    baseTime: t,
    timescale: e,
    trackId: i
  } = n;
  return `${t / e} (${t}/${e}) trackId: ${i}`;
}
const Ca = 10 * 1e3, _a = 1024, Pa = 1152, ka = 1536;
let Ut = null, ke = null;
function Qi(n, t, e, i) {
  return {
    duration: t,
    size: e,
    cts: i,
    flags: {
      isLeading: 0,
      isDependedOn: 0,
      hasRedundancy: 0,
      degradPrio: 0,
      dependsOn: n ? 2 : 1,
      isNonSync: n ? 0 : 1
    }
  };
}
class Oe extends Rt {
  constructor(t, e, 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 = t, this.config = e, this.typeSupported = i, this.ISGenerated = !1, Ut === null) {
      const a = (navigator.userAgent || "").match(/Chrome\/(\d+)/i);
      Ut = a ? parseInt(a[1]) : 0;
    }
    if (ke === null) {
      const r = navigator.userAgent.match(/Safari\/(\d+)/i);
      ke = r ? parseInt(r[1]) : 0;
    }
  }
  destroy() {
    this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  }
  resetTimeStamp(t) {
    const e = this._initPTS;
    (!e || !t || t.trackId !== e.trackId || t.baseTime !== e.baseTime || t.timescale !== e.timescale) && this.log(`Reset initPTS: ${e && Xi(e)} > ${t && Xi(t)}`), this._initPTS = this._initDTS = t;
  }
  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(t) {
    let e = !1;
    const i = t[0].pts, s = t.reduce((r, a) => {
      let o = a.pts, u = o - r;
      return u < -4294967296 && (e = !0, o = ht(o, i), u = o - r), u > 0 ? r : o;
    }, i);
    return e && this.debug("PTS rollover detected"), s;
  }
  remux(t, e, i, s, r, a, o, u) {
    let l, d, h, c, f, g, p = r, m = r;
    const y = t.pid > -1, T = e.pid > -1, v = e.samples.length, x = t.samples.length > 0, A = o && v > 0 || v > 1;
    if ((!y || x) && (!T || A) || this.ISGenerated || o) {
      if (this.ISGenerated) {
        var S, R, b, I;
        const V = this.videoTrackConfig;
        (V && (e.width !== V.width || e.height !== V.height || ((S = e.pixelRatio) == null ? void 0 : S[0]) !== ((R = V.pixelRatio) == null ? void 0 : R[0]) || ((b = e.pixelRatio) == null ? void 0 : b[1]) !== ((I = V.pixelRatio) == null ? void 0 : I[1])) || !V && A || this.nextAudioTs === null && x) && this.resetInitSegment();
      }
      this.ISGenerated || (h = this.generateIS(t, e, r, a));
      const _ = this.isVideoContiguous;
      let F = -1, $;
      if (A && (F = Oa(e.samples), !_ && this.config.forceKeyFrameOnDiscontinuity))
        if (g = !0, F > 0) {
          this.warn(`Dropped ${F} out of ${v} video samples due to a missing keyframe`);
          const V = this.getVideoStartPts(e.samples);
          e.samples = e.samples.slice(F), e.dropped += F, m += (e.samples[0].pts - V) / e.inputTimeScale, $ = m;
        } else F === -1 && (this.warn(`No keyframe found out of ${v} video samples`), g = !1);
      if (this.ISGenerated) {
        if (x && A) {
          const V = this.getVideoStartPts(e.samples), P = (ht(t.samples[0].pts, V) - V) / e.inputTimeScale;
          p += Math.max(0, P), m += Math.max(0, -P);
        }
        if (x) {
          if (t.samplerate || (this.warn("regenerate InitSegment as audio detected"), h = this.generateIS(t, e, r, a)), d = this.remuxAudio(t, p, this.isAudioContiguous, a, T || A || u === W.AUDIO ? m : void 0), A) {
            const V = d ? d.endPTS - d.startPTS : 0;
            e.inputTimeScale || (this.warn("regenerate InitSegment as video detected"), h = this.generateIS(t, e, r, a)), l = this.remuxVideo(e, m, _, V);
          }
        } else A && (l = this.remuxVideo(e, m, _, 0));
        l && (l.firstKeyFrame = F, l.independent = F !== -1, l.firstKeyFramePTS = $);
      }
    }
    return this.ISGenerated && this._initPTS && this._initDTS && (i.samples.length && (f = er(i, r, this._initPTS, this._initDTS)), s.samples.length && (c = ir(s, r, this._initPTS))), {
      audio: d,
      video: l,
      initSegment: h,
      independent: g,
      text: c,
      id3: f
    };
  }
  computeInitPts(t, e, i, s) {
    const r = Math.round(i * e);
    let a = ht(t, r);
    if (a < r + e)
      for (this.log(`Adjusting PTS for rollover in timeline near ${(r - a) / e} ${s}`); a < r + e; )
        a += 8589934592;
    return a - r;
  }
  generateIS(t, e, i, s) {
    const r = t.samples, a = e.samples, o = this.typeSupported, u = {}, l = this._initPTS;
    let d = !l || s, h = "audio/mp4", c, f, g, p = -1;
    if (d && (c = f = 1 / 0), t.config && r.length) {
      switch (t.timescale = t.samplerate, t.segmentCodec) {
        case "mp3":
          o.mpeg ? (h = "audio/mpeg", t.codec = "") : o.mp3 && (t.codec = "mp3");
          break;
        case "ac3":
          t.codec = "ac-3";
          break;
      }
      u.audio = {
        id: "audio",
        container: h,
        codec: t.codec,
        initSegment: t.segmentCodec === "mp3" && o.mpeg ? new Uint8Array(0) : L.initSegment([t]),
        metadata: {
          channelCount: t.channelCount
        }
      }, d && (p = t.id, g = t.inputTimeScale, !l || g !== l.timescale ? c = f = this.computeInitPts(r[0].pts, g, i, "audio") : d = !1);
    }
    if (e.sps && e.pps && a.length) {
      if (e.timescale = e.inputTimeScale, u.video = {
        id: "main",
        container: "video/mp4",
        codec: e.codec,
        initSegment: L.initSegment([e]),
        metadata: {
          width: e.width,
          height: e.height
        }
      }, d)
        if (p = e.id, g = e.inputTimeScale, !l || g !== l.timescale) {
          const m = this.getVideoStartPts(a), y = ht(a[0].dts, m), T = this.computeInitPts(y, g, i, "video"), v = this.computeInitPts(m, g, i, "video");
          f = Math.min(f, T), c = Math.min(c, v);
        } else
          d = !1;
      this.videoTrackConfig = {
        width: e.width,
        height: e.height,
        pixelRatio: e.pixelRatio
      };
    }
    if (Object.keys(u).length)
      return this.ISGenerated = !0, d ? (l && this.warn(`Timestamps at playlist time: ${s ? "" : "~"}${i} ${c / g} != initPTS: ${l.baseTime / l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`), this.log(`Found initPTS at playlist time: ${i} offset: ${c / g} (${c}/${g}) trackId: ${p}`), this._initPTS = {
        baseTime: c,
        timescale: g,
        trackId: p
      }, this._initDTS = {
        baseTime: f,
        timescale: g,
        trackId: p
      }) : c = g = void 0, {
        tracks: u,
        initPTS: c,
        timescale: g,
        trackId: p
      };
  }
  remuxVideo(t, e, i, s) {
    const r = t.inputTimeScale, a = t.samples, o = [], u = a.length, l = this._initPTS, d = l.baseTime * r / l.timescale;
    let h = this.nextVideoTs, c = 8, f = this.videoSampleDuration, g, p, m = Number.POSITIVE_INFINITY, y = Number.NEGATIVE_INFINITY, T = !1;
    if (!i || h === null) {
      const O = d + e * r, w = a[0].pts - ht(a[0].dts, a[0].pts);
      Ut && h !== null && Math.abs(O - w - (h + d)) < 15e3 ? i = !0 : h = O - w - d;
    }
    const v = h + d;
    for (let O = 0; O < u; O++) {
      const w = a[O];
      w.pts = ht(w.pts, v), w.dts = ht(w.dts, v), w.dts < a[O > 0 ? O - 1 : O].dts && (T = !0);
    }
    T && a.sort(function(O, w) {
      const z = O.dts - w.dts, Z = O.pts - w.pts;
      return z || Z;
    }), g = a[0].dts, p = a[a.length - 1].dts;
    const x = p - g, A = x ? Math.round(x / (u - 1)) : f || t.inputTimeScale / 30;
    if (i) {
      const O = g - v, w = O > A, z = O < -1;
      if ((w || z) && (w ? this.warn(`${(t.segmentCodec || "").toUpperCase()}: ${Kt(O, !0)} ms (${O}dts) hole between fragments detected at ${e.toFixed(3)}`) : this.warn(`${(t.segmentCodec || "").toUpperCase()}: ${Kt(-O, !0)} ms (${O}dts) overlapping between fragments detected at ${e.toFixed(3)}`), !z || v >= a[0].pts || Ut)) {
        g = v;
        const Z = a[0].pts - O;
        if (w)
          a[0].dts = g, a[0].pts = Z;
        else {
          let Q = !0;
          for (let et = 0; et < a.length && !(a[et].dts > Z && Q); et++) {
            const pt = a[et].pts;
            if (a[et].dts -= O, a[et].pts -= O, et < a.length - 1) {
              const xt = a[et + 1].pts, Mt = a[et].pts, kt = xt <= Mt, Ht = xt <= pt;
              Q = kt == Ht;
            }
          }
        }
        this.log(`Video: Initial PTS/DTS adjusted: ${Kt(Z, !0)}/${Kt(g, !0)}, delta: ${Kt(O, !0)} ms`);
      }
    }
    g = Math.max(0, g);
    let C = 0, S = 0, R = g;
    for (let O = 0; O < u; O++) {
      const w = a[O], z = w.units, Z = z.length;
      let Q = 0;
      for (let et = 0; et < Z; et++)
        Q += z[et].data.length;
      S += Q, C += Z, w.length = Q, w.dts < R ? (w.dts = R, R += A / 4 | 0 || 1) : R = w.dts, m = Math.min(w.pts, m), y = Math.max(w.pts, y);
    }
    p = a[u - 1].dts;
    const b = S + 4 * C + 8;
    let I;
    try {
      I = new Uint8Array(b);
    } catch (O) {
      this.observer.emit(E.ERROR, E.ERROR, {
        type: Y.MUX_ERROR,
        details: D.REMUX_ALLOC_ERROR,
        fatal: !1,
        error: O,
        bytes: b,
        reason: `fail allocating video mdat ${b}`
      });
      return;
    }
    const _ = new DataView(I.buffer);
    _.setUint32(0, b), I.set(L.types.mdat, 4);
    let F = !1, $ = Number.POSITIVE_INFINITY, V = Number.POSITIVE_INFINITY, N = Number.NEGATIVE_INFINITY, P = Number.NEGATIVE_INFINITY;
    for (let O = 0; O < u; O++) {
      const w = a[O], z = w.units;
      let Z = 0;
      for (let pt = 0, xt = z.length; pt < xt; pt++) {
        const Mt = z[pt], kt = Mt.data, Ht = Mt.data.byteLength;
        _.setUint32(c, Ht), c += 4, I.set(kt, c), c += Ht, Z += 4 + Ht;
      }
      let Q;
      if (O < u - 1)
        f = a[O + 1].dts - w.dts, Q = a[O + 1].pts - w.pts;
      else {
        const pt = this.config, xt = O > 0 ? w.dts - a[O - 1].dts : A;
        if (Q = O > 0 ? w.pts - a[O - 1].pts : A, pt.stretchShortVideoTrack && this.nextAudioTs !== null) {
          const Mt = Math.floor(pt.maxBufferHole * r), kt = (s ? m + s * r : this.nextAudioTs + d) - w.pts;
          kt > Mt ? (f = kt - xt, f < 0 ? f = xt : F = !0, this.log(`It is approximately ${kt / 90} ms to the next segment; using duration ${f / 90} ms for the last video frame.`)) : f = xt;
        } else
          f = xt;
      }
      const et = Math.round(w.pts - w.dts);
      $ = Math.min($, f), N = Math.max(N, f), V = Math.min(V, Q), P = Math.max(P, Q), o.push(Qi(w.key, f, Z, et));
    }
    if (o.length) {
      if (Ut) {
        if (Ut < 70) {
          const O = o[0].flags;
          O.dependsOn = 2, O.isNonSync = 0;
        }
      } else if (ke && P - V < N - $ && A / N < 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 O = g;
        for (let w = 0, z = o.length; w < z; w++) {
          const Z = O + o[w].duration, Q = O + o[w].cts;
          if (w < z - 1) {
            const et = Z + o[w + 1].cts;
            o[w].duration = et - Q;
          } else
            o[w].duration = w ? o[w - 1].duration : A;
          o[w].cts = 0, O = Z;
        }
      }
    }
    f = F || !f ? A : f;
    const G = p + f;
    this.nextVideoTs = h = G - d, this.videoSampleDuration = f, this.isVideoContiguous = !0;
    const H = {
      data1: L.moof(t.sequenceNumber++, g, nt(t, {
        samples: o
      })),
      data2: I,
      startPTS: (m - d) / r,
      endPTS: (y + f - d) / r,
      startDTS: (g - d) / r,
      endDTS: h / r,
      type: "video",
      hasAudio: !1,
      hasVideo: !0,
      nb: o.length,
      dropped: t.dropped
    };
    return t.samples = [], t.dropped = 0, H;
  }
  getSamplesPerFrame(t) {
    switch (t.segmentCodec) {
      case "mp3":
        return Pa;
      case "ac3":
        return ka;
      default:
        return _a;
    }
  }
  remuxAudio(t, e, i, s, r) {
    const a = t.inputTimeScale, o = t.samplerate ? t.samplerate : a, u = a / o, l = this.getSamplesPerFrame(t), d = l * u, h = this._initPTS, c = t.segmentCodec === "mp3" && this.typeSupported.mpeg, f = [], g = r !== void 0;
    let p = t.samples, m = c ? 0 : 8, y = this.nextAudioTs || -1;
    const T = h.baseTime * a / h.timescale, v = T + e * a;
    if (this.isAudioContiguous = i = i || p.length && y > 0 && (s && Math.abs(v - (y + T)) < 9e3 || Math.abs(ht(p[0].pts, v) - (y + T)) < 20 * d), p.forEach(function(P) {
      P.pts = ht(P.pts, v);
    }), !i || y < 0) {
      const P = p.length;
      if (p = p.filter((G) => G.pts >= 0), P !== p.length && this.warn(`Removed ${p.length - P} of ${P} samples (initPTS ${T} / ${a})`), !p.length)
        return;
      r === 0 ? y = 0 : s && !g ? y = Math.max(0, v - T) : y = p[0].pts - T;
    }
    if (t.segmentCodec === "aac") {
      const P = this.config.maxAudioFramesDrift;
      for (let G = 0, M = y + T; G < p.length; G++) {
        const U = p[G], H = U.pts, O = H - M, w = Math.abs(1e3 * O / a);
        if (O <= -P * d && g)
          G === 0 && (this.warn(`Audio frame @ ${(H / a).toFixed(3)}s overlaps marker by ${Math.round(1e3 * O / a)} ms.`), this.nextAudioTs = y = H - T, M = H);
        else if (O >= P * d && w < Ca && g) {
          let z = Math.round(O / d);
          for (M = H - z * d; M < 0 && z && d; )
            z--, M += d;
          G === 0 && (this.nextAudioTs = y = M - T), this.warn(`Injecting ${z} audio frames @ ${((M - T) / a).toFixed(3)}s due to ${Math.round(1e3 * O / a)} ms gap.`);
          for (let Z = 0; Z < z; Z++) {
            let Q = ba.getSilentFrame(t.parsedCodec || t.manifestCodec || t.codec, t.channelCount);
            Q || (this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."), Q = U.unit.subarray()), p.splice(G, 0, {
              unit: Q,
              pts: M
            }), M += d, G++;
          }
        }
        U.pts = M, M += d;
      }
    }
    let x = null, A = null, C, S = 0, R = p.length;
    for (; R--; )
      S += p[R].unit.byteLength;
    for (let P = 0, G = p.length; P < G; P++) {
      const M = p[P], U = M.unit;
      let H = M.pts;
      if (A !== null) {
        const w = f[P - 1];
        w.duration = Math.round((H - A) / u);
      } else if (i && t.segmentCodec === "aac" && (H = y + T), x = H, S > 0) {
        S += m;
        try {
          C = new Uint8Array(S);
        } catch (w) {
          this.observer.emit(E.ERROR, E.ERROR, {
            type: Y.MUX_ERROR,
            details: D.REMUX_ALLOC_ERROR,
            fatal: !1,
            error: w,
            bytes: S,
            reason: `fail allocating audio mdat ${S}`
          });
          return;
        }
        c || (new DataView(C.buffer).setUint32(0, S), C.set(L.types.mdat, 4));
      } else
        return;
      C.set(U, m);
      const O = U.byteLength;
      m += O, f.push(Qi(!0, l, O, 0)), A = H;
    }
    const b = f.length;
    if (!b)
      return;
    const I = f[f.length - 1];
    y = A - T, this.nextAudioTs = y + u * I.duration;
    const _ = c ? new Uint8Array(0) : L.moof(t.sequenceNumber++, x / u, nt({}, t, {
      samples: f
    }));
    t.samples = [];
    const F = (x - T) / a, $ = y / a, N = {
      data1: _,
      data2: C,
      startPTS: F,
      endPTS: $,
      startDTS: F,
      endDTS: $,
      type: "audio",
      hasAudio: !0,
      hasVideo: !1,
      nb: b
    };
    return this.isAudioContiguous = !0, N;
  }
}
function ht(n, t) {
  let e;
  if (t === null)
    return n;
  for (t < n ? e = -8589934592 : e = 8589934592; Math.abs(n - t) > 4294967296; )
    n += e;
  return n;
}
function Oa(n) {
  for (let t = 0; t < n.length; t++)
    if (n[t].key)
      return t;
  return -1;
}
function er(n, t, e, i) {
  const s = n.samples.length;
  if (!s)
    return;
  const r = n.inputTimeScale;
  for (let o = 0; o < s; o++) {
    const u = n.samples[o];
    u.pts = ht(u.pts - e.baseTime * r / e.timescale, t * r) / r, u.dts = ht(u.dts - i.baseTime * r / i.timescale, t * r) / r;
  }
  const a = n.samples;
  return n.samples = [], {
    samples: a
  };
}
function ir(n, t, e) {
  const i = n.samples.length;
  if (!i)
    return;
  const s = n.inputTimeScale;
  for (let a = 0; a < i; a++) {
    const o = n.samples[a];
    o.pts = ht(o.pts - e.baseTime * s / e.timescale, t * s) / s;
  }
  n.samples.sort((a, o) => a.pts - o.pts);
  const r = n.samples;
  return n.samples = [], {
    samples: r
  };
}
class wa extends Rt {
  constructor(t, e, 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(t) {
    this.lastEndTime = null;
    const e = this.initPTS;
    e && t && e.baseTime === t.baseTime && e.timescale === t.timescale || (this.initPTS = t);
  }
  resetNextTimestamp() {
    this.isVideoContiguous = !1, this.lastEndTime = null;
  }
  resetInitSegment(t, e, i, s) {
    this.audioCodec = e, this.videoCodec = i, this.generateInitSegment(t, s), this.emitInitSegment = !0;
  }
  generateInitSegment(t, e) {
    let {
      audioCodec: i,
      videoCodec: s
    } = this;
    if (!(t != null && t.byteLength)) {
      this.initTracks = void 0, this.initData = void 0;
      return;
    }
    const {
      audio: r,
      video: a
    } = this.initData = ms(t);
    if (e)
      Dr(t, e);
    else {
      const u = r || a;
      u != null && u.encrypted && this.warn(`Init segment with encrypted track with has no key ("${u.codec}")!`);
    }
    r && (i = Zi(r, tt.AUDIO, this)), a && (s = Zi(a, tt.VIDEO, this));
    const o = {};
    r && a ? o.audiovideo = {
      container: "video/mp4",
      codec: i + "," + s,
      supplemental: a.supplemental,
      encrypted: a.encrypted,
      initSegment: t,
      id: "main"
    } : r ? o.audio = {
      container: "audio/mp4",
      codec: i,
      encrypted: r.encrypted,
      initSegment: t,
      id: "audio"
    } : a ? o.video = {
      container: "video/mp4",
      codec: s,
      supplemental: a.supplemental,
      encrypted: a.encrypted,
      initSegment: t,
      id: "main"
    } : this.warn("initSegment does not contain moov or trak boxes."), this.initTracks = o;
  }
  remux(t, e, i, s, r, a) {
    var o, u;
    let {
      initPTS: l,
      lastEndTime: d
    } = this;
    const h = {
      audio: void 0,
      video: void 0,
      text: s,
      id3: i,
      initSegment: void 0
    };
    B(d) || (d = this.lastEndTime = r || 0);
    const c = e.samples;
    if (!c.length)
      return h;
    const f = {
      initPTS: void 0,
      timescale: void 0,
      trackId: void 0
    };
    let g = this.initData;
    if ((o = g) != null && o.length || (this.generateInitSegment(c), g = this.initData), !((u = g) != null && u.length))
      return this.warn("Failed to generate initSegment."), h;
    this.emitInitSegment && (f.tracks = this.initTracks, this.emitInitSegment = !1);
    const p = Pr(c, g, this), m = g.audio ? p[g.audio.id] : null, y = g.video ? p[g.video.id] : null, T = ne(y, 1 / 0), v = ne(m, 1 / 0), x = ne(y, 0, !0), A = ne(m, 0, !0);
    let C = r, S = 0;
    const R = m && (!y || !l && v < T || l && l.trackId === g.audio.id), b = R ? m : y;
    if (b) {
      const M = b.timescale, U = b.start - r * M, H = R ? g.audio.id : g.video.id;
      C = b.start / M, S = R ? A - v : x - T, (a || !l) && (Fa(l, C, r, S) || M !== l.timescale) && (l && this.warn(`Timestamps at playlist time: ${a ? "" : "~"}${r} ${U / M} != initPTS: ${l.baseTime / l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`), this.log(`Found initPTS at playlist time: ${r} offset: ${C - r} (${U}/${M}) trackId: ${H}`), l = null, f.initPTS = U, f.timescale = M, f.trackId = H);
    } else
      this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);
    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 = C, f.timescale = 1, f.trackId = -1), this.initPTS = l = {
      baseTime: f.initPTS,
      timescale: f.timescale,
      trackId: f.trackId
    });
    const I = C - l.baseTime / l.timescale, _ = I + S;
    S > 0 ? this.lastEndTime = _ : (this.warn("Duration parsed from mp4 should be greater than zero"), this.resetNextTimestamp());
    const F = !!g.audio, $ = !!g.video;
    let V = "";
    F && (V += "audio"), $ && (V += "video");
    const N = (g.audio ? g.audio.encrypted : !1) || (g.video ? g.video.encrypted : !1), P = {
      data1: c,
      startPTS: I,
      startDTS: I,
      endPTS: _,
      endDTS: _,
      type: V,
      hasAudio: F,
      hasVideo: $,
      nb: 1,
      dropped: 0,
      encrypted: N
    };
    h.audio = F && !$ ? P : void 0, h.video = $ ? P : void 0;
    const G = y?.sampleCount;
    if (G) {
      const M = y.keyFrameIndex, U = M !== -1;
      P.nb = G, P.dropped = M === 0 || this.isVideoContiguous ? 0 : U ? M : G, P.independent = U, P.firstKeyFrame = M, U && y.keyFrameStart && (P.firstKeyFramePTS = (y.keyFrameStart - l.baseTime) / l.timescale), this.isVideoContiguous || (h.independent = U), this.isVideoContiguous || (this.isVideoContiguous = U), P.dropped && this.warn(`fmp4 does not start with IDR: firstIDR ${M}/${G} dropped: ${P.dropped} start: ${P.firstKeyFramePTS || "NA"}`);
    }
    return h.initSegment = f, h.id3 = er(i, r, l, l), s.samples.length && (h.text = ir(s, r, l)), h;
  }
}
function ne(n, t, e = !1) {
  return n?.start !== void 0 ? (n.start + (e ? n.duration : 0)) / n.timescale : t;
}
function Fa(n, t, e, i) {
  if (n === null)
    return !0;
  const s = Math.max(i, 1), r = t - n.baseTime / n.timescale;
  return Math.abs(r - e) > s;
}
function Zi(n, t, e) {
  const i = n.codec;
  return i && i.length > 4 ? i : t === tt.AUDIO ? i === "ec-3" || i === "ac-3" || i === "alac" ? i : i === "fLaC" || i === "Opus" ? ce(i, !1) : (e.warn(`Unhandled audio codec "${i}" in mp4 MAP`), i || "mp4a") : (e.warn(`Unhandled video codec "${i}" in mp4 MAP`), i || "avc1");
}
let At;
try {
  At = self.performance.now.bind(self.performance);
} catch {
  At = Date.now;
}
const we = [{
  demux: Ta,
  remux: wa
}, {
  demux: Dt,
  remux: Oe
}, {
  demux: pa,
  remux: Oe
}, {
  demux: va,
  remux: Oe
}];
class Ji {
  constructor(t, e, i, s, r, 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 = t, this.typeSupported = e, this.config = i, this.id = r, this.logger = a;
  }
  configure(t) {
    this.transmuxConfig = t, this.decrypter && this.decrypter.reset();
  }
  push(t, e, i, s) {
    const r = i.transmuxing;
    r.executeStart = At();
    let a = new Uint8Array(t);
    const {
      currentTransmuxState: o,
      transmuxConfig: u
    } = this;
    s && (this.currentTransmuxState = s);
    const {
      contiguous: l,
      discontinuity: d,
      trackSwitch: h,
      accurateTimeOffset: c,
      timeOffset: f,
      initSegmentChange: g
    } = s || o, {
      audioCodec: p,
      videoCodec: m,
      defaultInitPts: y,
      duration: T,
      initSegmentData: v
    } = u, x = Ma(a, e);
    if (x && Yt(x.method)) {
      const R = this.getDecrypter(), b = Is(x.method);
      if (R.isSync()) {
        let I = R.softwareDecrypt(a, x.key.buffer, x.iv.buffer, b);
        if (i.part > -1) {
          const F = R.flush();
          I = F && F.buffer;
        }
        if (!I)
          return r.executeEnd = At(), Fe(i);
        a = new Uint8Array(I);
      } else
        return this.asyncResult = !0, this.decryptionPromise = R.webCryptoDecrypt(a, x.key.buffer, x.iv.buffer, b).then((I) => {
          const _ = this.push(I, null, i);
          return this.decryptionPromise = null, _;
        }), this.decryptionPromise;
    }
    const A = this.needsProbing(d, h);
    if (A) {
      const R = this.configureTransmuxer(a);
      if (R)
        return this.logger.warn(`[transmuxer] ${R.message}`), this.observer.emit(E.ERROR, E.ERROR, {
          type: Y.MEDIA_ERROR,
          details: D.FRAG_PARSING_ERROR,
          fatal: !1,
          error: R,
          reason: R.message
        }), r.executeEnd = At(), Fe(i);
    }
    (d || h || g || A) && this.resetInitSegment(v, p, m, T, e), (d || g || A) && this.resetInitialTimestamp(y), l || this.resetContiguity();
    const C = this.transmux(a, x, f, c, i);
    this.asyncResult = Qt(C);
    const S = this.currentTransmuxState;
    return S.contiguous = !0, S.discontinuity = !1, S.trackSwitch = !1, r.executeEnd = At(), C;
  }
  // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  flush(t) {
    const e = t.transmuxing;
    e.executeStart = At();
    const {
      decrypter: i,
      currentTransmuxState: s,
      decryptionPromise: r
    } = this;
    if (r)
      return this.asyncResult = !0, r.then(() => this.flush(t));
    const a = [], {
      timeOffset: o
    } = s;
    if (i) {
      const h = i.flush();
      h && a.push(this.push(h.buffer, null, t));
    }
    const {
      demuxer: u,
      remuxer: l
    } = this;
    if (!u || !l) {
      e.executeEnd = At();
      const h = [Fe(t)];
      return this.asyncResult ? Promise.resolve(h) : h;
    }
    const d = u.flush(o);
    return Qt(d) ? (this.asyncResult = !0, d.then((h) => (this.flushRemux(a, h, t), a))) : (this.flushRemux(a, d, t), this.asyncResult ? Promise.resolve(a) : a);
  }
  flushRemux(t, e, i) {
    const {
      audioTrack: s,
      videoTrack: r,
      id3Track: a,
      textTrack: o
    } = e, {
      accurateTimeOffset: u,
      timeOffset: l
    } = this.currentTransmuxState;
    this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part > -1 ? " part: " + i.part : ""} of ${this.id === W.MAIN ? "level" : "track"} ${i.level}`);
    const d = this.remuxer.remux(s, r, a, o, l, u, !0, this.id);
    t.push({
      remuxResult: d,
      chunkMeta: i
    }), i.transmuxing.executeEnd = At();
  }
  resetInitialTimestamp(t) {
    const {
      demuxer: e,
      remuxer: i
    } = this;
    !e || !i || (e.resetTimeStamp(t), i.resetTimeStamp(t));
  }
  resetContiguity() {
    const {
      demuxer: t,
      remuxer: e
    } = this;
    !t || !e || (t.resetContiguity(), e.resetNextTimestamp());
  }
  resetInitSegment(t, e, i, s, r) {
    const {
      demuxer: a,
      remuxer: o
    } = this;
    !a || !o || (a.resetInitSegment(t, e, i, s), o.resetInitSegment(t, e, i, r));
  }
  destroy() {
    this.demuxer && (this.demuxer.destroy(), this.demuxer = void 0), this.remuxer && (this.remuxer.destroy(), this.remuxer = void 0);
  }
  transmux(t, e, i, s, r) {
    let a;
    return e && e.method === "SAMPLE-AES" ? a = this.transmuxSampleAes(t, e, i, s, r) : a = this.transmuxUnencrypted(t, i, s, r), a;
  }
  transmuxUnencrypted(t, e, i, s) {
    const {
      audioTrack: r,
      videoTrack: a,
      id3Track: o,
      textTrack: u
    } = this.demuxer.demux(t, e, !1, !this.config.progressive);
    return {
      remuxResult: this.remuxer.remux(r, a, o, u, e, i, !1, this.id),
      chunkMeta: s
    };
  }
  transmuxSampleAes(t, e, i, s, r) {
    return this.demuxer.demuxSampleAes(t, e, i).then((a) => ({
      remuxResult: this.remuxer.remux(a.audioTrack, a.videoTrack, a.id3Track, a.textTrack, i, s, !1, this.id),
      chunkMeta: r
    }));
  }
  configureTransmuxer(t) {
    const {
      config: e,
      observer: i,
      typeSupported: s
    } = this;
    let r;
    for (let h = 0, c = we.length; h < c; h++) {
      var a;
      if ((a = we[h].demux) != null && a.probe(t, this.logger)) {
        r = we[h];
        break;
      }
    }
    if (!r)
      return new Error("Failed to find demuxer by probing fragment data");
    const o = this.demuxer, u = this.remuxer, l = r.remux, d = r.demux;
    (!u || !(u instanceof l)) && (this.remuxer = new l(i, e, s, this.logger)), (!o || !(o instanceof d)) && (this.demuxer = new d(i, e, s, this.logger), this.probe = d.probe);
  }
  needsProbing(t, e) {
    return !this.demuxer || !this.remuxer || t || e;
  }
  getDecrypter() {
    let t = this.decrypter;
    return t || (t = this.decrypter = new ti(this.config)), t;
  }
}
function Ma(n, t) {
  let e = null;
  return n.byteLength > 0 && t?.key != null && t.iv !== null && t.method != null && (e = t), e;
}
const Fe = (n) => ({
  remuxResult: {},
  chunkMeta: n
});
function Qt(n) {
  return "then" in n && n.then instanceof Function;
}
class Na {
  constructor(t, e, i, s, r) {
    this.audioCodec = void 0, this.videoCodec = void 0, this.initSegmentData = void 0, this.duration = void 0, this.defaultInitPts = void 0, this.audioCodec = t, this.videoCodec = e, this.initSegmentData = i, this.duration = s, this.defaultInitPts = r || null;
  }
}
class Ba {
  constructor(t, e, i, s, r, 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 = t, this.contiguous = e, this.accurateTimeOffset = i, this.trackSwitch = s, this.timeOffset = r, this.initSegmentChange = a;
  }
}
function $a() {
  if (
    // @ts-ignore
    self.fetch && self.AbortController && self.ReadableStream && self.Request
  )
    try {
      return new self.ReadableStream({}), !0;
    } catch {
    }
  return !1;
}
const Ua = /(\d+)-(\d+)\/(\d+)/;
class ts {
  constructor(t) {
    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 = t.fetchSetup || Ka, this.controller = new self.AbortController(), this.stats = new qe();
  }
  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 t;
    this.abortInternal(), (t = this.callbacks) != null && t.onAbort && this.callbacks.onAbort(this.stats, this.context, this.response);
  }
  load(t, e, 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 r = Ga(t, this.controller.signal), a = t.responseType === "arraybuffer", o = a ? "byteLength" : "length", {
      maxTimeToFirstByteMs: u,
      maxLoadTimeMs: l
    } = e.loadPolicy;
    this.context = t, this.config = e, this.callbacks = i, this.request = this.fetchSetup(t, r), self.clearTimeout(this.requestTimeout), e.timeout = u && B(u) ? u : l, this.requestTimeout = self.setTimeout(() => {
      this.callbacks && (this.abortInternal(), this.callbacks.onTimeout(s, t, this.response));
    }, e.timeout), (Qt(this.request) ? this.request.then(self.fetch) : self.fetch(this.request)).then((h) => {
      var c;
      this.response = this.loader = h;
      const f = Math.max(self.performance.now(), s.loading.start);
      if (self.clearTimeout(this.requestTimeout), e.timeout = l, this.requestTimeout = self.setTimeout(() => {
        this.callbacks && (this.abortInternal(), this.callbacks.onTimeout(s, t, this.response));
      }, l - (f - s.loading.start)), !h.ok) {
        const {
          status: p,
          statusText: m
        } = h;
        throw new Wa(m || "fetch, bad network response", p, h);
      }
      s.loading.first = f, s.total = Ha(h.headers) || s.total;
      const g = (c = this.callbacks) == null ? void 0 : c.onProgress;
      return g && B(e.highWaterMark) ? this.loadProgressively(h, s, t, e.highWaterMark, g) : a ? h.arrayBuffer() : t.responseType === "json" ? h.json() : h.text();
    }).then((h) => {
      var c, f;
      const g = this.response;
      if (!g)
        throw new Error("loader destroyed");
      self.clearTimeout(this.requestTimeout), s.loading.end = Math.max(self.performance.now(), s.loading.first);
      const p = h[o];
      p && (s.loaded = s.total = p);
      const m = {
        url: g.url,
        data: h,
        code: g.status
      }, y = (c = this.callbacks) == null ? void 0 : c.onProgress;
      y && !B(e.highWaterMark) && y(s, t, h, g), (f = this.callbacks) == null || f.onSuccess(m, s, t, g);
    }).catch((h) => {
      var c;
      if (self.clearTimeout(this.requestTimeout), s.aborted)
        return;
      const f = h && h.code || 0, g = h ? h.message : null;
      (c = this.callbacks) == null || c.onError({
        code: f,
        text: g
      }, t, h ? h.details : null, s);
    });
  }
  getCacheAge() {
    let t = null;
    if (this.response) {
      const e = this.response.headers.get("age");
      t = e ? parseFloat(e) : null;
    }
    return t;
  }
  getResponseHeader(t) {
    return this.response ? this.response.headers.get(t) : null;
  }
  loadProgressively(t, e, i, s = 0, r) {
    const a = new Kn(), o = t.body.getReader(), u = () => o.read().then((l) => {
      if (l.done)
        return a.dataLength && r(e, i, a.flush().buffer, t), Promise.resolve(new ArrayBuffer(0));
      const d = l.value, h = d.length;
      return e.loaded += h, h < s || a.dataLength ? (a.push(d), a.dataLength >= s && r(e, i, a.flush().buffer, t)) : r(e, i, d.buffer, t), u();
    }).catch(() => Promise.reject());
    return u();
  }
}
function Ga(n, t) {
  const e = {
    method: "GET",
    mode: "cors",
    credentials: "same-origin",
    signal: t,
    headers: new self.Headers(nt({}, n.headers))
  };
  return n.rangeEnd && e.headers.set("Range", "bytes=" + n.rangeStart + "-" + String(n.rangeEnd - 1)), e;
}
function Va(n) {
  const t = Ua.exec(n);
  if (t)
    return parseInt(t[2]) - parseInt(t[1]) + 1;
}
function Ha(n) {
  const t = n.get("Content-Range");
  if (t) {
    const i = Va(t);
    if (B(i))
      return i;
  }
  const e = n.get("Content-Length");
  if (e)
    return parseInt(e);
}
function Ka(n, t) {
  return new self.Request(n.url, t);
}
class Wa extends Error {
  constructor(t, e, i) {
    super(t), this.code = void 0, this.details = void 0, this.code = e, this.details = i;
  }
}
const Ya = /^age:\s*[\d.]+\s*$/im;
class sr {
  constructor(t) {
    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 = t && t.xhrSetup || null, this.stats = new qe(), this.retryDelay = 0;
  }
  destroy() {
    this.callbacks = null, this.abortInternal(), this.loader = null, this.config = null, this.context = null, this.xhrSetup = null;
  }
  abortInternal() {
    const t = this.loader;
    self.clearTimeout(this.requestTimeout), self.clearTimeout(this.retryTimeout), t && (t.onreadystatechange = null, t.onprogress = null, t.readyState !== 4 && (this.stats.aborted = !0, t.abort()));
  }
  abort() {
    var t;
    this.abortInternal(), (t = this.callbacks) != null && t.onAbort && this.callbacks.onAbort(this.stats, this.context, this.loader);
  }
  load(t, e, i) {
    if (this.stats.loading.start)
      throw new Error("Loader can only be used once.");
    this.stats.loading.start = self.performance.now(), this.context = t, this.config = e, this.callbacks = i, this.loadInternal();
  }
  loadInternal() {
    const {
      config: t,
      context: e
    } = this;
    if (!t || !e)
      return;
    const i = this.loader = new self.XMLHttpRequest(), s = this.stats;
    s.loading.first = 0, s.loaded = 0, s.aborted = !1;
    const r = this.xhrSetup;
    r ? Promise.resolve().then(() => {
      if (!(this.loader !== i || this.stats.aborted))
        return r(i, e.url);
    }).catch((a) => {
      if (!(this.loader !== i || this.stats.aborted))
        return i.open("GET", e.url, !0), r(i, e.url);
    }).then(() => {
      this.loader !== i || this.stats.aborted || this.openAndSendXhr(i, e, t);
    }).catch((a) => {
      var o;
      (o = this.callbacks) == null || o.onError({
        code: i.status,
        text: a.message
      }, e, i, s);
    }) : this.openAndSendXhr(i, e, t);
  }
  openAndSendXhr(t, e, i) {
    t.readyState || t.open("GET", e.url, !0);
    const s = e.headers, {
      maxTimeToFirstByteMs: r,
      maxLoadTimeMs: a
    } = i.loadPolicy;
    if (s)
      for (const o in s)
        t.setRequestHeader(o, s[o]);
    e.rangeEnd && t.setRequestHeader("Range", "bytes=" + e.rangeStart + "-" + (e.rangeEnd - 1)), t.onreadystatechange = this.readystatechange.bind(this), t.onprogress = this.loadprogress.bind(this), t.responseType = e.responseType, self.clearTimeout(this.requestTimeout), i.timeout = r && B(r) ? r : a, this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), i.timeout), t.send();
  }
  readystatechange() {
    const {
      context: t,
      loader: e,
      stats: i
    } = this;
    if (!t || !e)
      return;
    const s = e.readyState, r = this.config;
    if (!i.aborted && s >= 2 && (i.loading.first === 0 && (i.loading.first = Math.max(self.performance.now(), i.loading.start), r.timeout !== r.loadPolicy.maxLoadTimeMs && (self.clearTimeout(this.requestTimeout), r.timeout = r.loadPolicy.maxLoadTimeMs, this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), r.loadPolicy.maxLoadTimeMs - (i.loading.first - i.loading.start)))), s === 4)) {
      self.clearTimeout(this.requestTimeout), e.onreadystatechange = null, e.onprogress = null;
      const l = e.status, d = e.responseType === "text" ? e.responseText : null;
      if (l >= 200 && l < 300) {
        const g = d ?? e.response;
        if (g != null) {
          var a, o;
          i.loading.end = Math.max(self.performance.now(), i.loading.first);
          const p = e.responseType === "arraybuffer" ? g.byteLength : g.length;
          i.loaded = i.total = p, i.bwEstimate = i.total * 8e3 / (i.loading.end - i.loading.first);
          const m = (a = this.callbacks) == null ? void 0 : a.onProgress;
          m && m(i, t, g, e);
          const y = {
            url: e.responseURL,
            data: g,
            code: l
          };
          (o = this.callbacks) == null || o.onSuccess(y, i, t, e);
          return;
        }
      }
      const h = r.loadPolicy.errorRetry, c = i.retry, f = {
        url: t.url,
        data: void 0,
        code: l
      };
      if (me(h, c, !1, f))
        this.retry(h);
      else {
        var u;
        J.error(`${l} while loading ${t.url}`), (u = this.callbacks) == null || u.onError({
          code: l,
          text: e.statusText
        }, t, e, i);
      }
    }
  }
  loadtimeout() {
    if (!this.config) return;
    const t = this.config.loadPolicy.timeoutRetry, e = this.stats.retry;
    if (me(t, e, !0))
      this.retry(t);
    else {
      var i;
      J.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(t) {
    const {
      context: e,
      stats: i
    } = this;
    this.retryDelay = Je(t, i.retry), i.retry++, J.warn(`${status ? "HTTP Status " + status : "Timeout"} while loading ${e?.url}, retrying ${i.retry}/${t.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(t) {
    const e = this.stats;
    e.loaded = t.loaded, t.lengthComputable && (e.total = t.total);
  }
  getCacheAge() {
    let t = null;
    if (this.loader && Ya.test(this.loader.getAllResponseHeaders())) {
      const e = this.loader.getResponseHeader("age");
      t = e ? parseFloat(e) : null;
    }
    return t;
  }
  getResponseHeader(t) {
    return this.loader && new RegExp(`^${t}:\\s*[\\d.]+\\s*$`, "im").test(this.loader.getAllResponseHeaders()) ? this.loader.getResponseHeader(t) : null;
  }
}
const es = {
  maxTimeToFirstByteMs: 8e3,
  maxLoadTimeMs: 2e4,
  timeoutRetry: null,
  errorRetry: null
}, ja = ct(ct({
  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: sr,
  // 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: jr,
  bufferController: Mn,
  capLevelController: ei,
  errorController: Jr,
  fpsController: Un,
  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: null,
  // 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: !1,
  interstitialAppendInPlace: !0,
  interstitialLiveLookAhead: 10,
  useMediaCapabilities: !1,
  preserveManualLevelOnError: !1,
  certLoadPolicy: {
    default: es
  },
  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: es
  },
  // 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
}, qa()), {}, {
  subtitleStreamController: void 0,
  subtitleTrackController: void 0,
  timelineController: void 0,
  audioStreamController: void 0,
  audioTrackController: void 0,
  emeController: void 0,
  cmcdController: void 0,
  contentSteeringController: $n,
  interstitialsController: void 0
});
function qa() {
  return {
    cueHandler: Er,
    // used by timeline-controller
    enableWebVTT: !1,
    // used by timeline-controller
    enableIMSC1: !1,
    // used by timeline-controller
    enableCEA708Captions: !1,
    // 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 za(n, t, e) {
  if ((t.liveSyncDurationCount || t.liveMaxLatencyDurationCount) && (t.liveSyncDuration || t.liveMaxLatencyDuration))
    throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  if (t.liveMaxLatencyDurationCount !== void 0 && (t.liveSyncDurationCount === void 0 || t.liveMaxLatencyDurationCount <= t.liveSyncDurationCount))
    throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  if (t.liveMaxLatencyDuration !== void 0 && (t.liveSyncDuration === void 0 || t.liveMaxLatencyDuration <= t.liveSyncDuration))
    throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  const i = We(n), s = ["manifest", "level", "frag"], r = ["TimeOut", "MaxRetry", "RetryDelay", "MaxRetryTimeout"];
  return s.forEach((a) => {
    const o = `${a === "level" ? "playlist" : a}LoadPolicy`, u = t[o] === void 0, l = [];
    r.forEach((d) => {
      const h = `${a}Loading${d}`, c = t[h];
      if (c !== void 0 && u) {
        l.push(h);
        const f = i[o].default;
        switch (t[o] = {
          default: f
        }, d) {
          case "TimeOut":
            f.maxLoadTimeMs = c, f.maxTimeToFirstByteMs = c;
            break;
          case "MaxRetry":
            f.errorRetry.maxNumRetry = c, f.timeoutRetry.maxNumRetry = c;
            break;
          case "RetryDelay":
            f.errorRetry.retryDelayMs = c, f.timeoutRetry.retryDelayMs = c;
            break;
          case "MaxRetryTimeout":
            f.errorRetry.maxRetryDelayMs = c, f.timeoutRetry.maxRetryDelayMs = c;
            break;
        }
      }
    }), l.length && e.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ot(t[o])}`);
  }), ct(ct({}, i), t);
}
function We(n) {
  return n && typeof n == "object" ? Array.isArray(n) ? n.map(We) : Object.keys(n).reduce((t, e) => (t[e] = We(n[e]), t), {}) : n;
}
function Xa(n, t) {
  const e = n.loader;
  e !== ts && e !== sr ? (t.log("[config]: Custom loader detected, cannot enable progressive streaming"), n.progressive = !1) : $a() && (n.loader = ts, n.progressive = !0, n.enableSoftwareAES = !0, t.log("[config]: Progressive streaming enabled, using FetchLoader"));
}
const de = 2, Qa = 0.1, Za = 0.05, Ja = 100;
class to extends Fs {
  constructor(t, e) {
    super("gap-controller", t.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(E.MEDIA_ENDED, {
          stalled: !1
        });
      }
    }, this.hls = t, this.fragmentTracker = e, this.registerListeners();
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t && (t.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.on(E.BUFFER_APPENDED, this.onBufferAppended, this));
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t && (t.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.off(E.BUFFER_APPENDED, this.onBufferAppended, this));
  }
  destroy() {
    super.destroy(), this.unregisterListeners(), this.media = this.hls = this.fragmentTracker = null, this.mediaSource = void 0;
  }
  onMediaAttached(t, e) {
    this.setInterval(Ja), this.mediaSource = e.mediaSource;
    const i = this.media = e.media;
    wt(i, "playing", this.onMediaPlaying), wt(i, "waiting", this.onMediaWaiting), wt(i, "ended", this.onMediaEnded);
  }
  onMediaDetaching(t, e) {
    this.clearInterval();
    const {
      media: i
    } = this;
    i && (Ct(i, "playing", this.onMediaPlaying), Ct(i, "waiting", this.onMediaWaiting), Ct(i, "ended", this.onMediaEnded), this.media = null), this.mediaSource = void 0;
  }
  onBufferAppended(t, e) {
    this.buffered = e.timeRanges;
  }
  get hasBuffered() {
    return Object.keys(this.buffered).length > 0;
  }
  tick() {
    var t;
    if (!((t = this.media) != null && t.readyState) || !this.hasBuffered)
      return;
    const e = this.media.currentTime;
    this.poll(e, this.lastCurrentTime), this.lastCurrentTime = e;
  }
  /**
   * 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(t, e) {
    var i, s;
    const r = (i = this.hls) == null ? void 0 : i.config;
    if (!r)
      return;
    const a = this.media;
    if (!a)
      return;
    const {
      seeking: o
    } = a, u = this.seeking && !o, l = !this.seeking && o, d = a.paused && !o || a.ended || a.playbackRate === 0;
    if (this.seeking = o, t !== e) {
      e && (this.ended = 0), this.moved = !0, o || (this.nudgeRetry = 0, r.nudgeOnVideoHole && !d && t > e && this.nudgeOnVideoHole(t, e)), this.waiting === 0 && this.stallResolved(t);
      return;
    }
    if (l || u) {
      u && this.stallResolved(t);
      return;
    }
    if (d) {
      this.nudgeRetry = 0, this.stallResolved(t), !this.ended && a.ended && this.hls && (this.ended = t || 1, this.hls.trigger(E.MEDIA_ENDED, {
        stalled: !1
      }));
      return;
    }
    if (!q.getBuffered(a).length) {
      this.nudgeRetry = 0;
      return;
    }
    const h = q.bufferInfo(a, t, 0), c = h.nextStart || 0, f = this.fragmentTracker;
    if (o && f && this.hls) {
      const C = is(this.hls.inFlightFragments, t), S = h.len > de, R = !c || C || c - t > de && !f.getPartialFragment(t);
      if (S || R)
        return;
      this.moved = !1;
    }
    const g = (s = this.hls) == null ? void 0 : s.latestLevelDetails;
    if (!this.moved && this.stalled !== null && f) {
      if (!(h.len > 0) && !c)
        return;
      const S = Math.max(c, h.start || 0) - t, b = !!(g != null && g.live) ? g.targetduration * 2 : de, I = ae(t, f);
      if (S > 0 && (S <= b || I)) {
        a.paused || this._trySkipBufferHole(I);
        return;
      }
    }
    const p = r.detectStallWithCurrentTimeMs, m = self.performance.now(), y = this.waiting;
    let T = this.stalled;
    if (T === null)
      if (y > 0 && m - y < p)
        T = this.stalled = y;
      else {
        this.stalled = m;
        return;
      }
    const v = m - T;
    if (!o && (v >= p || y) && this.hls) {
      var x;
      if (((x = this.mediaSource) == null ? void 0 : x.readyState) === "ended" && !(g != null && g.live) && Math.abs(t - (g?.edge || 0)) < 1) {
        if (this.ended)
          return;
        this.ended = t || 1, this.hls.trigger(E.MEDIA_ENDED, {
          stalled: !0
        });
        return;
      }
      if (this._reportStall(h), !this.media || !this.hls)
        return;
    }
    const A = q.bufferInfo(a, t, r.maxBufferHole);
    this._tryFixBufferStall(A, v, t);
  }
  stallResolved(t) {
    const e = this.stalled;
    if (e && this.hls && (this.stalled = null, this.stallReported)) {
      const i = self.performance.now() - e;
      this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`), this.stallReported = !1, this.waiting = 0, this.hls.trigger(E.STALL_RESOLVED, {});
    }
  }
  nudgeOnVideoHole(t, e) {
    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 && t > s.end(0)) {
      const r = q.bufferedInfo(q.timeRangesToArray(this.buffered.audio), t, 0);
      if (r.len > 1 && e >= r.start) {
        const a = q.timeRangesToArray(s), o = q.bufferedInfo(a, e, 0).bufferedIndex;
        if (o > -1 && o < a.length - 1) {
          const u = q.bufferedInfo(a, t, 0).bufferedIndex, l = a[o].end, d = a[o + 1].start;
          if ((u === -1 || u > o) && d - l < 1 && // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
          t - l < 2) {
            const h = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${l} -> ${d} buffered index: ${u}`);
            this.warn(h.message), this.media.currentTime += 1e-6;
            let c = ae(t, this.fragmentTracker);
            c && "fragment" in c ? c = c.fragment : c || (c = void 0);
            const f = q.bufferInfo(this.media, t, 0);
            this.hls.trigger(E.ERROR, {
              type: Y.MEDIA_ERROR,
              details: D.BUFFER_SEEK_OVER_HOLE,
              fatal: !1,
              error: h,
              reason: h.message,
              frag: c,
              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(t, e, i) {
    var s, r;
    const {
      fragmentTracker: a,
      media: o
    } = this, u = (s = this.hls) == null ? void 0 : s.config;
    if (!o || !a || !u)
      return;
    const l = (r = this.hls) == null ? void 0 : r.latestLevelDetails, d = ae(i, a);
    if ((d || l != null && l.live && i < l.fragmentStart) && (this._trySkipBufferHole(d) || !this.media))
      return;
    const h = t.buffered, c = this.adjacentTraversal(t, i);
    (h && h.length > 1 && t.len > u.maxBufferHole || t.nextStart && (t.nextStart - i < u.maxBufferHole || c)) && (e > u.highBufferWatchdogPeriod * 1e3 || this.waiting) && (this.warn("Trying to nudge playhead over buffer-hole"), this._tryNudgeBuffer(t));
  }
  adjacentTraversal(t, e) {
    const i = this.fragmentTracker, s = t.nextStart;
    if (i && s) {
      const r = i.getFragAtPos(e, W.MAIN), a = i.getFragAtPos(s, W.MAIN);
      if (r && a)
        return a.sn - r.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(t) {
    const {
      hls: e,
      media: i,
      stallReported: s,
      stalled: r
    } = this;
    if (!s && r !== null && i && e) {
      this.stallReported = !0;
      const a = new Error(`Playback stalling at @${i.currentTime} due to low buffer (${ot(t)})`);
      this.warn(a.message), e.trigger(E.ERROR, {
        type: Y.MEDIA_ERROR,
        details: D.BUFFER_STALLED_ERROR,
        fatal: !1,
        error: a,
        buffer: t.len,
        bufferInfo: t,
        stalled: {
          start: r
        }
      });
    }
  }
  /**
   * 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(t) {
    var e;
    const {
      fragmentTracker: i,
      media: s
    } = this, r = (e = this.hls) == null ? void 0 : e.config;
    if (!s || !i || !r)
      return 0;
    const a = s.currentTime, o = q.bufferInfo(s, a, 0), u = a < o.start ? o.start : o.nextStart;
    if (u && this.hls) {
      const d = o.len <= r.maxBufferHole, h = o.len > 0 && o.len < 1 && s.readyState < 3, c = u - a;
      if (c > 0 && (d || h)) {
        if (c > r.maxBufferHole) {
          let g = !1;
          if (a === 0) {
            const p = i.getAppendedFrag(0, W.MAIN);
            p && u < p.end && (g = !0);
          }
          if (!g && t) {
            var l;
            if (!((l = this.hls.loadLevelObj) != null && l.details) || is(this.hls.inFlightFragments, u))
              return 0;
            let m = !1, y = t.end;
            for (; y < u; ) {
              const T = ae(y, i);
              if (T)
                y += T.duration;
              else {
                m = !0;
                break;
              }
            }
            if (m)
              return 0;
          }
        }
        const f = Math.max(u + Za, a + Qa);
        if (this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`), this.moved = !0, s.currentTime = f, !(t != null && t.gap)) {
          const g = new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`), p = {
            type: Y.MEDIA_ERROR,
            details: D.BUFFER_SEEK_OVER_HOLE,
            fatal: !1,
            error: g,
            reason: g.message,
            buffer: o.len,
            bufferInfo: o
          };
          t && ("fragment" in t ? p.part = t : p.frag = t), this.hls.trigger(E.ERROR, p);
        }
        return f;
      }
    }
    return 0;
  }
  /**
   * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
   * @private
   */
  _tryNudgeBuffer(t) {
    const {
      hls: e,
      media: i,
      nudgeRetry: s
    } = this, r = e?.config;
    if (!i || !r)
      return 0;
    const a = i.currentTime;
    if (this.nudgeRetry++, s < r.nudgeMaxRetry) {
      const o = a + (s + 1) * r.nudgeOffset, u = new Error(`Nudging 'currentTime' from ${a} to ${o}`);
      this.warn(u.message), i.currentTime = o, e.trigger(E.ERROR, {
        type: Y.MEDIA_ERROR,
        details: D.BUFFER_NUDGE_ON_STALL,
        error: u,
        fatal: !1,
        buffer: t.len,
        bufferInfo: t
      });
    } else {
      const o = new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);
      this.error(o.message), e.trigger(E.ERROR, {
        type: Y.MEDIA_ERROR,
        details: D.BUFFER_STALLED_ERROR,
        error: o,
        fatal: !0,
        buffer: t.len,
        bufferInfo: t
      });
    }
  }
}
function is(n, t) {
  const e = ss(n.main);
  if (e && e.start <= t)
    return e;
  const i = ss(n.audio);
  return i && i.start <= t ? i : null;
}
function ss(n) {
  if (!n)
    return null;
  switch (n.state) {
    case k.IDLE:
    case k.STOPPED:
    case k.ENDED:
    case k.ERROR:
      return null;
  }
  return n.frag;
}
function ae(n, t) {
  return t.getAppendedFrag(n, W.MAIN) || t.getPartialFragment(n);
}
function eo(n, t) {
  let e;
  try {
    e = new Event("addtrack");
  } catch {
    e = document.createEvent("Event"), e.initEvent("addtrack", !1, !1);
  }
  e.track = n, t.dispatchEvent(e);
}
function io(n, t) {
  const e = n.mode;
  if (e === "disabled" && (n.mode = "hidden"), n.cues)
    for (let i = n.cues.length; i--; )
      t && n.cues[i].removeEventListener("enter", t), n.removeCue(n.cues[i]);
  e === "disabled" && (n.mode = e);
}
function so(n, t, e, i) {
  const s = n.mode;
  if (s === "disabled" && (n.mode = "hidden"), n.cues && n.cues.length > 0) {
    const r = no(n.cues, t, e);
    for (let a = 0; a < r.length; a++)
      (!i || i(r[a])) && n.removeCue(r[a]);
  }
  s === "disabled" && (n.mode = s);
}
function ro(n, t) {
  if (t <= n[0].startTime)
    return 0;
  const e = n.length - 1;
  if (t > n[e].endTime)
    return -1;
  let i = 0, s = e, r;
  for (; i <= s; )
    if (r = Math.floor((s + i) / 2), t < n[r].startTime)
      s = r - 1;
    else if (t > n[r].startTime && i < e)
      i = r + 1;
    else
      return r;
  return n[i].startTime - t < t - n[s].startTime ? i : s;
}
function no(n, t, e) {
  const i = [], s = ro(n, t);
  if (s > -1)
    for (let r = s, a = n.length; r < a; r++) {
      const o = n[r];
      if (o.startTime >= t && o.endTime <= e)
        i.push(o);
      else if (o.startTime > e)
        return i;
    }
  return i;
}
const ao = 0.25;
function Ye() {
  if (!(typeof self > "u"))
    return self.VTTCue || self.TextTrackCue;
}
function rs(n, t, e, i, s) {
  let r = new n(t, e, "");
  try {
    r.value = i, s && (r.type = s);
  } catch {
    r = new n(t, e, ot(s ? ct({
      type: s
    }, i) : i));
  }
  return r;
}
const oe = (() => {
  const n = Ye();
  try {
    n && new n(0, Number.POSITIVE_INFINITY, "");
  } catch {
    return Number.MAX_VALUE;
  }
  return Number.POSITIVE_INFINITY;
})();
class oo {
  constructor(t) {
    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(E.EVENT_CUE_ENTER, {});
    }, this.hls = t, this._registerListeners();
  }
  destroy() {
    this._unregisterListeners(), this.id3Track = null, this.media = null, this.dateRangeCuesAppended = {}, this.hls = this.onEventCueEnter = null;
  }
  _registerListeners() {
    const {
      hls: t
    } = this;
    t && (t.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this), t.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), t.on(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.on(E.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this));
  }
  _unregisterListeners() {
    const {
      hls: t
    } = this;
    t && (t.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), t.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this), t.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), t.off(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.off(E.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this));
  }
  // Add ID3 metatadata text track.
  onMediaAttaching(t, e) {
    var i;
    this.media = e.media, ((i = e.overrides) == null ? void 0 : i.cueRemoval) === !1 && (this.removeCues = !1);
  }
  onMediaAttached() {
    var t;
    const e = (t = this.hls) == null ? void 0 : t.latestLevelDetails;
    e && this.updateDateRangeCues(e);
  }
  onMediaDetaching(t, e) {
    this.media = null, !e.transferMedia && (this.id3Track && (this.removeCues && io(this.id3Track, this.onEventCueEnter), this.id3Track = null), this.dateRangeCuesAppended = {});
  }
  onManifestLoading() {
    this.dateRangeCuesAppended = {};
  }
  createTrack(t) {
    const e = this.getID3Track(t.textTracks);
    return e.mode = "hidden", e;
  }
  getID3Track(t) {
    if (this.media) {
      for (let e = 0; e < t.length; e++) {
        const i = t[e];
        if (i.kind === "metadata" && i.label === "id3")
          return eo(i, this.media), i;
      }
      return this.media.addTextTrack("metadata", "id3");
    }
  }
  onFragParsingMetadata(t, e) {
    if (!this.media || !this.hls)
      return;
    const {
      enableEmsgMetadataCues: i,
      enableID3MetadataCues: s
    } = this.hls.config;
    if (!i && !s)
      return;
    const {
      samples: r
    } = e;
    this.id3Track || (this.id3Track = this.createTrack(this.media));
    const a = Ye();
    if (a)
      for (let o = 0; o < r.length; o++) {
        const u = r[o].type;
        if (u === dt.emsg && !i || !s)
          continue;
        const l = js(r[o].data), d = r[o].pts;
        let h = d + r[o].duration;
        h > oe && (h = oe), h - d <= 0 && (h = d + ao);
        for (let f = 0; f < l.length; f++) {
          const g = l[f];
          if (!qs(g)) {
            this.updateId3CueEnds(d, u);
            const p = rs(a, d, h, g, u);
            p && this.id3Track.addCue(p);
          }
        }
      }
  }
  updateId3CueEnds(t, e) {
    var i;
    const s = (i = this.id3Track) == null ? void 0 : i.cues;
    if (s)
      for (let r = s.length; r--; ) {
        const a = s[r];
        a.type === e && a.startTime < t && a.endTime === oe && (a.endTime = t);
      }
  }
  onBufferFlushing(t, {
    startOffset: e,
    endOffset: i,
    type: s
  }) {
    const {
      id3Track: r,
      hls: a
    } = this;
    if (!a)
      return;
    const {
      config: {
        enableEmsgMetadataCues: o,
        enableID3MetadataCues: u
      }
    } = a;
    if (r && (o || u)) {
      let l;
      s === "audio" ? l = (d) => d.type === dt.audioId3 && u : s === "video" ? l = (d) => d.type === dt.emsg && o : l = (d) => d.type === dt.audioId3 && u || d.type === dt.emsg && o, so(r, e, i, l);
    }
  }
  onLevelUpdated(t, {
    details: e
  }) {
    this.updateDateRangeCues(e, !0);
  }
  onLevelPtsUpdated(t, e) {
    Math.abs(e.drift) > 0.01 && this.updateDateRangeCues(e.details);
  }
  updateDateRangeCues(t, e) {
    if (!this.hls || !this.media)
      return;
    const {
      assetPlayerId: i,
      timelineOffset: s,
      enableDateRangeMetadataCues: r,
      interstitialsController: a
    } = this.hls.config;
    if (!r)
      return;
    const o = Ye();
    if (!t.hasProgramDateTime)
      return;
    const {
      id3Track: u
    } = this, {
      dateRanges: l
    } = t, d = Object.keys(l);
    let h = this.dateRangeCuesAppended;
    if (u && e) {
      var c;
      if ((c = u.cues) != null && c.length) {
        const p = Object.keys(h).filter((m) => !d.includes(m));
        for (let m = p.length; m--; ) {
          var f;
          const y = p[m], T = (f = h[y]) == null ? void 0 : f.cues;
          delete h[y], T && Object.keys(T).forEach((v) => {
            const x = T[v];
            if (x) {
              x.removeEventListener("enter", this.onEventCueEnter);
              try {
                u.removeCue(x);
              } catch {
              }
            }
          });
        }
      } else
        h = this.dateRangeCuesAppended = {};
    }
    const g = t.fragments[t.fragments.length - 1];
    if (!(d.length === 0 || !B(g?.programDateTime))) {
      this.id3Track || (this.id3Track = this.createTrack(this.media));
      for (let p = 0; p < d.length; p++) {
        const m = d[p], y = l[m], T = y.startTime, v = h[m], x = v?.cues || {};
        let A = v?.durationKnown || !1, C = oe;
        const {
          duration: S,
          endDate: R
        } = y;
        if (R && S !== null)
          C = T + S, A = !0;
        else if (y.endOnNext && !A) {
          const I = d.reduce((_, F) => {
            if (F !== y.id) {
              const $ = l[F];
              if ($.class === y.class && $.startDate > y.startDate && (!_ || y.startDate < _.startDate))
                return $;
            }
            return _;
          }, null);
          I && (C = I.startTime, A = !0);
        }
        const b = Object.keys(y.attr);
        for (let I = 0; I < b.length; I++) {
          const _ = b[I];
          if (!sn(_))
            continue;
          const F = x[_];
          if (F)
            A && !(v != null && v.durationKnown) ? F.endTime = C : Math.abs(F.startTime - T) > 0.01 && (F.startTime = T, F.endTime = C);
          else if (o) {
            let $ = y.attr[_];
            rn(_) && ($ = us($));
            const N = rs(o, T, C, {
              key: _,
              data: $
            }, dt.dateRange);
            N && (N.id = m, this.id3Track.addCue(N), x[_] = N);
          }
        }
        h[m] = {
          cues: x,
          dateRange: y,
          durationKnown: A
        };
      }
    }
  }
}
class lo {
  constructor(t) {
    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: e
      } = this, i = this.levelDetails;
      if (!e || !i)
        return;
      this.currentTime = e.currentTime;
      const s = this.computeLatency();
      if (s === null)
        return;
      this._latency = s;
      const {
        lowLatencyMode: r,
        maxLiveSyncPlaybackRate: a
      } = this.config;
      if (!r || a === 1 || !i.live)
        return;
      const o = this.targetLatency;
      if (o === null)
        return;
      const u = s - o, l = Math.min(this.maxLatency, o + i.targetduration);
      if (u < l && u > 0.05 && this.forwardBufferLength > 1) {
        const h = Math.min(2, Math.max(1, a)), c = Math.round(2 / (1 + Math.exp(-0.75 * u - this.edgeStalled)) * 20) / 20, f = Math.min(h, Math.max(1, c));
        this.changeMediaPlaybackRate(e, f);
      } else e.playbackRate !== 1 && e.playbackRate !== 0 && this.changeMediaPlaybackRate(e, 1);
    }, this.hls = t, this.config = t.config, this.registerListeners();
  }
  get levelDetails() {
    var t;
    return ((t = this.hls) == null ? void 0 : t.latestLevelDetails) || null;
  }
  get latency() {
    return this._latency || 0;
  }
  get maxLatency() {
    const {
      config: t
    } = this;
    if (t.liveMaxLatencyDuration !== void 0)
      return t.liveMaxLatencyDuration;
    const e = this.levelDetails;
    return e ? t.liveMaxLatencyDurationCount * e.targetduration : 0;
  }
  get targetLatency() {
    const t = this.levelDetails;
    if (t === null || this.hls === null)
      return null;
    const {
      holdBack: e,
      partHoldBack: i,
      targetduration: s
    } = t, {
      liveSyncDuration: r,
      liveSyncDurationCount: a,
      lowLatencyMode: o
    } = this.config, u = this.hls.userConfig;
    let l = o && i || e;
    (this._targetLatencyUpdated || u.liveSyncDuration || u.liveSyncDurationCount || l === 0) && (l = r !== void 0 ? r : a * s);
    const d = s;
    return l + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, d);
  }
  set targetLatency(t) {
    this.stallCount = 0, this.config.liveSyncDuration = t, this._targetLatencyUpdated = !0;
  }
  get liveSyncPosition() {
    const t = this.estimateLiveEdge(), e = this.targetLatency;
    if (t === null || e === null)
      return null;
    const i = this.levelDetails;
    if (i === null)
      return null;
    const s = i.edge, r = t - e - this.edgeStalled, a = s - i.totalduration, o = s - (this.config.lowLatencyMode && i.partTarget || i.targetduration);
    return Math.min(Math.max(a, r), o);
  }
  get drift() {
    const t = this.levelDetails;
    return t === null ? 1 : t.drift;
  }
  get edgeStalled() {
    const t = this.levelDetails;
    if (t === null)
      return 0;
    const e = (this.config.lowLatencyMode && t.partTarget || t.targetduration) * 3;
    return Math.max(t.age - e, 0);
  }
  get forwardBufferLength() {
    const {
      media: t
    } = this, e = this.levelDetails;
    if (!t || !e)
      return 0;
    const i = t.buffered.length;
    return (i ? t.buffered.end(i - 1) : e.edge) - this.currentTime;
  }
  destroy() {
    this.unregisterListeners(), this.onMediaDetaching(), this.hls = null;
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t && (t.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.on(E.ERROR, this.onError, this));
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t && (t.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), t.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.LEVEL_UPDATED, this.onLevelUpdated, this), t.off(E.ERROR, this.onError, this));
  }
  onMediaAttached(t, e) {
    this.media = e.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(t, {
    details: e
  }) {
    e.advanced && this.onTimeupdate(), !e.live && this.media && this.media.removeEventListener("timeupdate", this.onTimeupdate);
  }
  onError(t, e) {
    var i;
    e.details === D.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(t, e) {
    var i, s;
    t.playbackRate !== e && ((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 ${t.playbackRate} to ${e}`), t.playbackRate = e);
  }
  estimateLiveEdge() {
    const t = this.levelDetails;
    return t === null ? null : t.edge + t.age;
  }
  computeLatency() {
    const t = this.estimateLiveEdge();
    return t === null ? null : t - this.currentTime;
  }
}
class uo extends vn {
  constructor(t, e) {
    super(t, "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 = e, this._registerListeners();
  }
  _registerListeners() {
    const {
      hls: t
    } = this;
    t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.on(E.LEVEL_LOADED, this.onLevelLoaded, this), t.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.on(E.FRAG_BUFFERED, this.onFragBuffered, this), t.on(E.ERROR, this.onError, this);
  }
  _unregisterListeners() {
    const {
      hls: t
    } = this;
    t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), t.off(E.LEVEL_LOADED, this.onLevelLoaded, this), t.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.off(E.FRAG_BUFFERED, this.onFragBuffered, this), t.off(E.ERROR, this.onError, this);
  }
  destroy() {
    this._unregisterListeners(), this.steering = null, this.resetLevels(), super.destroy();
  }
  stopLoad() {
    this._levels.forEach((e) => {
      e.loadError = 0, e.fragmentError = 0;
    }), super.stopLoad();
  }
  resetLevels() {
    this._startLevel = void 0, this.manualLevelIndex = -1, this.currentLevelIndex = -1, this.currentLevel = null, this._levels = [], this._maxAutoLevel = -1;
  }
  onManifestLoading(t, e) {
    this.resetLevels();
  }
  onManifestLoaded(t, e) {
    const i = this.hls.config.preferManagedMediaSource, s = [], r = {}, a = {};
    let o = !1, u = !1, l = !1;
    e.levels.forEach((d) => {
      const h = d.attrs;
      let {
        audioCodec: c,
        videoCodec: f
      } = d;
      c && (d.audioCodec = c = ce(c, i) || void 0), f && (f = d.videoCodec = Br(f));
      const {
        width: g,
        height: p,
        unknownCodecs: m
      } = d, y = m?.length || 0;
      if (o || (o = !!(g && p)), u || (u = !!f), l || (l = !!c), y || c && !this.isAudioSupported(c) || f && !this.isVideoSupported(f)) {
        this.log(`Some or all CODECS not supported "${h.CODECS}"`);
        return;
      }
      const {
        CODECS: T,
        "FRAME-RATE": v,
        "HDCP-LEVEL": x,
        "PATHWAY-ID": A,
        RESOLUTION: C,
        "VIDEO-RANGE": S
      } = h, b = `${`${A || "."}-`}${d.bitrate}-${C}-${v}-${T}-${S}-${x}`;
      if (r[b])
        if (r[b].uri !== d.url && !d.attrs["PATHWAY-ID"]) {
          const I = a[b] += 1;
          d.attrs["PATHWAY-ID"] = new Array(I + 1).join(".");
          const _ = this.createLevel(d);
          r[b] = _, s.push(_);
        } else
          r[b].addGroupId("audio", h.AUDIO), r[b].addGroupId("text", h.SUBTITLES);
      else {
        const I = this.createLevel(d);
        r[b] = I, a[b] = 1, s.push(I);
      }
    }), this.filterAndSortMediaOptions(s, e, o, u, l);
  }
  createLevel(t) {
    const e = new Ts(t), i = t.supplemental;
    if (i != null && i.videoCodec && !this.isVideoSupported(i.videoCodec)) {
      const s = new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);
      this.log(s.message), e.supportedResult = Ft.getUnsupportedResult(s, []);
    }
    return e;
  }
  isAudioSupported(t) {
    return zt(t, "audio", this.hls.config.preferManagedMediaSource);
  }
  isVideoSupported(t) {
    return zt(t, "video", this.hls.config.preferManagedMediaSource);
  }
  filterAndSortMediaOptions(t, e, i, s, r) {
    var a;
    let o = [], u = [], l = t;
    const d = ((a = e.stats) == null ? void 0 : a.parsing) || {};
    if ((i || s) && r && (l = l.filter(({
      videoCodec: T,
      videoRange: v,
      width: x,
      height: A
    }) => (!!T || !!(x && A)) && Gr(v))), l.length === 0) {
      Promise.resolve().then(() => {
        if (this.hls) {
          let T = "no level with compatible codecs found in manifest", v = T;
          e.levels.length && (v = `one or more CODECS in variant not supported: ${ot(e.levels.map((A) => A.attrs.CODECS).filter((A, C, S) => S.indexOf(A) === C))}`, this.warn(v), T += ` (${v})`);
          const x = new Error(T);
          this.hls.trigger(E.ERROR, {
            type: Y.MEDIA_ERROR,
            details: D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
            fatal: !0,
            url: e.url,
            error: x,
            reason: v
          });
        }
      }), d.end = performance.now();
      return;
    }
    e.audioTracks && (o = e.audioTracks.filter((T) => !T.audioCodec || this.isAudioSupported(T.audioCodec)), ns(o)), e.subtitles && (u = e.subtitles, ns(u));
    const h = l.slice(0);
    l.sort((T, v) => {
      if (T.attrs["HDCP-LEVEL"] !== v.attrs["HDCP-LEVEL"])
        return (T.attrs["HDCP-LEVEL"] || "") > (v.attrs["HDCP-LEVEL"] || "") ? 1 : -1;
      if (i && T.height !== v.height)
        return T.height - v.height;
      if (T.frameRate !== v.frameRate)
        return T.frameRate - v.frameRate;
      if (T.videoRange !== v.videoRange)
        return fe.indexOf(T.videoRange) - fe.indexOf(v.videoRange);
      if (T.videoCodec !== v.videoCodec) {
        const x = ci(T.videoCodec), A = ci(v.videoCodec);
        if (x !== A)
          return A - x;
      }
      if (T.uri === v.uri && T.codecSet !== v.codecSet) {
        const x = he(T.codecSet), A = he(v.codecSet);
        if (x !== A)
          return A - x;
      }
      return T.averageBitrate !== v.averageBitrate ? T.averageBitrate - v.averageBitrate : 0;
    });
    let c = h[0];
    if (this.steering && (l = this.steering.filterParsedLevels(l), l.length !== h.length)) {
      for (let T = 0; T < h.length; T++)
        if (h[T].pathwayId === l[0].pathwayId) {
          c = h[T];
          break;
        }
    }
    this._levels = l;
    for (let T = 0; T < l.length; T++)
      if (l[T] === c) {
        var f;
        this._firstLevel = T;
        const v = c.bitrate, x = this.hls.bandwidthEstimate;
        if (this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${v}`), ((f = this.hls.userConfig) == null ? void 0 : f.abrEwmaDefaultEstimate) === void 0) {
          const A = Math.min(v, this.hls.config.abrEwmaDefaultEstimateMax);
          A > x && x === this.hls.abrEwmaDefaultEstimate && (this.hls.bandwidthEstimate = A);
        }
        break;
      }
    const g = r && !s, p = this.hls.config, m = !!(p.audioStreamController && p.audioTrackController), y = {
      levels: l,
      audioTracks: o,
      subtitleTracks: u,
      sessionData: e.sessionData,
      sessionKeys: e.sessionKeys,
      firstLevel: this._firstLevel,
      stats: e.stats,
      audio: r,
      video: s,
      altAudio: m && !g && o.some((T) => !!T.url)
    };
    d.end = performance.now(), this.hls.trigger(E.MANIFEST_PARSED, y);
  }
  get levels() {
    return this._levels.length === 0 ? null : this._levels;
  }
  get loadLevelObj() {
    return this.currentLevel;
  }
  get level() {
    return this.currentLevelIndex;
  }
  set level(t) {
    const e = this._levels;
    if (e.length === 0)
      return;
    if (t < 0 || t >= e.length) {
      const d = new Error("invalid level idx"), h = t < 0;
      if (this.hls.trigger(E.ERROR, {
        type: Y.OTHER_ERROR,
        details: D.LEVEL_SWITCH_ERROR,
        level: t,
        fatal: h,
        error: d,
        reason: d.message
      }), h)
        return;
      t = Math.min(t, e.length - 1);
    }
    const i = this.currentLevelIndex, s = this.currentLevel, r = s ? s.attrs["PATHWAY-ID"] : void 0, a = e[t], o = a.attrs["PATHWAY-ID"];
    if (this.currentLevelIndex = t, this.currentLevel = a, i === t && s && r === o)
      return;
    this.log(`Switching to level ${t} (${a.height ? a.height + "p " : ""}${a.videoRange ? a.videoRange + " " : ""}${a.codecSet ? a.codecSet + " " : ""}@${a.bitrate})${o ? " with Pathway " + o : ""} from level ${i}${r ? " with Pathway " + r : ""}`);
    const u = {
      level: t,
      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(E.LEVEL_SWITCHING, u);
    const l = a.details;
    if (!l || l.live) {
      const d = this.switchParams(a.uri, s?.details, l);
      this.loadPlaylist(d);
    }
  }
  get manualLevel() {
    return this.manualLevelIndex;
  }
  set manualLevel(t) {
    this.manualLevelIndex = t, this._startLevel === void 0 && (this._startLevel = t), t !== -1 && (this.level = t);
  }
  get firstLevel() {
    return this._firstLevel;
  }
  set firstLevel(t) {
    this._firstLevel = t;
  }
  get startLevel() {
    if (this._startLevel === void 0) {
      const t = this.hls.config.startLevel;
      return t !== void 0 ? t : this.hls.firstAutoLevel;
    }
    return this._startLevel;
  }
  set startLevel(t) {
    this._startLevel = t;
  }
  get pathways() {
    return this.steering ? this.steering.pathways() : [];
  }
  get pathwayPriority() {
    return this.steering ? this.steering.pathwayPriority : null;
  }
  set pathwayPriority(t) {
    if (this.steering) {
      const e = this.steering.pathways(), i = t.filter((s) => e.indexOf(s) !== -1);
      if (t.length < 1) {
        this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);
        return;
      }
      this.steering.pathwayPriority = i;
    }
  }
  onError(t, e) {
    e.fatal || !e.context || e.context.type === X.LEVEL && e.context.level === this.level && this.checkRetry(e);
  }
  // reset errors on the successful load of a fragment
  onFragBuffered(t, {
    frag: e
  }) {
    if (e !== void 0 && e.type === W.MAIN) {
      const i = e.elementaryStreams;
      if (!Object.keys(i).some((r) => !!i[r]))
        return;
      const s = this._levels[e.level];
      s != null && s.loadError && (this.log(`Resetting level error count of ${s.loadError} on frag buffered`), s.loadError = 0);
    }
  }
  onLevelLoaded(t, e) {
    var i;
    const {
      level: s,
      details: r
    } = e, a = e.levelInfo;
    if (!a) {
      var o;
      this.warn(`Invalid level index ${s}`), (o = e.deliveryDirectives) != null && o.skip && (r.deltaUpdateFailed = !0);
      return;
    }
    if (a === this.currentLevel || e.withoutMultiVariant) {
      a.fragmentError === 0 && (a.loadError = 0);
      let u = a.details;
      u === e.details && u.advanced && (u = void 0), this.playlistLoaded(s, e, u);
    } else (i = e.deliveryDirectives) != null && i.skip && (r.deltaUpdateFailed = !0);
  }
  loadPlaylist(t) {
    super.loadPlaylist(), this.shouldLoadPlaylist(this.currentLevel) && this.scheduleLoading(this.currentLevel, t);
  }
  loadingPlaylist(t, e) {
    super.loadingPlaylist(t, e);
    const i = this.getUrlWithDirectives(t.uri, e), s = this.currentLevelIndex, r = t.attrs["PATHWAY-ID"], a = t.details, o = a?.age;
    this.log(`Loading level index ${s}${e?.msn !== void 0 ? " at sn " + e.msn + " part " + e.part : ""}${r ? " Pathway " + r : ""}${o && a.live ? " age " + o.toFixed(1) + (a.type && " " + a.type || "") : ""} ${i}`), this.hls.trigger(E.LEVEL_LOADING, {
      url: i,
      level: s,
      levelInfo: t,
      pathwayId: t.attrs["PATHWAY-ID"],
      id: 0,
      // Deprecated Level urlId
      deliveryDirectives: e || null
    });
  }
  get nextLoadLevel() {
    return this.manualLevelIndex !== -1 ? this.manualLevelIndex : this.hls.nextAutoLevel;
  }
  set nextLoadLevel(t) {
    this.level = t, this.manualLevelIndex === -1 && (this.hls.nextAutoLevel = t);
  }
  removeLevel(t) {
    var e;
    if (this._levels.length === 1)
      return;
    const i = this._levels.filter((r, a) => a !== t ? !0 : (this.steering && this.steering.removeLevel(r), r === this.currentLevel && (this.currentLevel = null, this.currentLevelIndex = -1, r.details && r.details.fragments.forEach((o) => o.level = -1)), !1));
    ws(i), this._levels = i, this.currentLevelIndex > -1 && (e = this.currentLevel) != null && e.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(E.LEVELS_UPDATED, {
      levels: i
    });
  }
  onLevelsUpdated(t, {
    levels: e
  }) {
    this._levels = e;
  }
  checkMaxAutoUpdated() {
    const {
      autoLevelCapping: t,
      maxAutoLevel: e,
      maxHdcpLevel: i
    } = this.hls;
    this._maxAutoLevel !== e && (this._maxAutoLevel = e, this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED, {
      autoLevelCapping: t,
      levels: this.levels,
      maxAutoLevel: e,
      minAutoLevel: this.hls.minAutoLevel,
      maxHdcpLevel: i
    }));
  }
}
function ns(n) {
  const t = {};
  n.forEach((e) => {
    const i = e.groupId || "";
    e.id = t[i] = t[i] || 0, t[i]++;
  });
}
const Zt = "1.6.13", Vt = {};
function ho() {
  return typeof __HLS_WORKER_BUNDLE__ == "function";
}
function co() {
  const n = Vt[Zt];
  if (n)
    return n.clientCount++, n;
  const t = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
    type: "text/javascript"
  }), e = self.URL.createObjectURL(t), s = {
    worker: new self.Worker(e),
    objectURL: e,
    clientCount: 1
  };
  return Vt[Zt] = s, s;
}
function fo(n) {
  const t = Vt[n];
  if (t)
    return t.clientCount++, t;
  const e = new self.URL(n, self.location.href).href, s = {
    worker: new self.Worker(e),
    scriptURL: e,
    clientCount: 1
  };
  return Vt[n] = s, s;
}
function go(n) {
  const t = Vt[n || Zt];
  if (t && t.clientCount-- === 1) {
    const {
      worker: i,
      objectURL: s
    } = t;
    delete Vt[n || Zt], s && self.URL.revokeObjectURL(s), i.terminate();
  }
}
let as = 0;
class mo {
  constructor(t, e, i, s) {
    this.error = null, this.hls = void 0, this.id = void 0, this.instanceNo = as++, 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 = (u) => {
      const l = u.data, d = this.hls;
      if (!(!d || !(l != null && l.event) || l.instanceNo !== this.instanceNo))
        switch (l.event) {
          case "init": {
            var h;
            const c = (h = this.workerContext) == null ? void 0 : h.objectURL;
            c && self.URL.revokeObjectURL(c);
            break;
          }
          case "transmuxComplete": {
            this.handleTransmuxComplete(l.data);
            break;
          }
          case "flush": {
            this.onFlush(l.data);
            break;
          }
          // pass logs from the worker thread to the main logger
          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 = (u) => {
      if (!this.hls)
        return;
      const l = new Error(`${u.message}  (${u.filename}:${u.lineno})`);
      this.hls.config.enableWorker = !1, this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`), this.hls.trigger(E.ERROR, {
        type: Y.OTHER_ERROR,
        details: D.INTERNAL_EXCEPTION,
        fatal: !1,
        event: "demuxerWorker",
        error: l
      });
    };
    const r = t.config;
    this.hls = t, this.id = e, this.useWorker = !!r.enableWorker, this.onTransmuxComplete = i, this.onFlush = s;
    const a = (u, l) => {
      l = l || {}, l.frag = this.frag || void 0, u === E.ERROR && (l = l, l.parent = this.id, l.part = this.part, this.error = l.error), this.hls.trigger(u, l);
    };
    this.observer = new Us(), this.observer.on(E.FRAG_DECRYPTED, a), this.observer.on(E.ERROR, a);
    const o = gi(r.preferManagedMediaSource);
    if (this.useWorker && typeof Worker < "u") {
      const u = this.hls.logger;
      if (r.workerPath || ho()) {
        try {
          r.workerPath ? (u.log(`loading Web Worker ${r.workerPath} for "${e}"`), this.workerContext = fo(r.workerPath)) : (u.log(`injecting Web Worker for "${e}"`), this.workerContext = co());
          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: e,
            config: ot(r)
          });
        } catch (d) {
          u.warn(`Error setting up "${e}" Web Worker, fallback to inline`, d), this.terminateWorker(), this.error = null, this.transmuxer = new Ji(this.observer, o, r, "", e, t.logger);
        }
        return;
      }
    }
    this.transmuxer = new Ji(this.observer, o, r, "", e, t.logger);
  }
  reset() {
    if (this.frag = null, this.part = null, this.workerContext) {
      const t = this.instanceNo;
      this.instanceNo = as++;
      const e = this.hls.config, i = gi(e.preferManagedMediaSource);
      this.workerContext.worker.postMessage({
        instanceNo: this.instanceNo,
        cmd: "reset",
        resetNo: t,
        typeSupported: i,
        id: this.id,
        config: ot(e)
      });
    }
  }
  terminateWorker() {
    if (this.workerContext) {
      const {
        worker: t
      } = this.workerContext;
      this.workerContext = null, t.removeEventListener("message", this.onWorkerMessage), t.removeEventListener("error", this.onWorkerError), go(this.hls.config.workerPath);
    }
  }
  destroy() {
    if (this.workerContext)
      this.terminateWorker(), this.onWorkerMessage = this.onWorkerError = null;
    else {
      const e = this.transmuxer;
      e && (e.destroy(), this.transmuxer = null);
    }
    const t = this.observer;
    t && t.removeAllListeners(), this.frag = null, this.part = null, this.observer = null, this.hls = null;
  }
  push(t, e, i, s, r, a, o, u, l, d) {
    var h, c;
    l.transmuxing.start = self.performance.now();
    const {
      instanceNo: f,
      transmuxer: g
    } = this, p = a ? a.start : r.start, m = r.decryptdata, y = this.frag, T = !(y && r.cc === y.cc), v = !(y && l.level === y.level), x = y ? l.sn - y.sn : -1, A = this.part ? l.part - this.part.index : -1, C = x === 0 && l.id > 1 && l.id === y?.stats.chunkCount, S = !v && (x === 1 || x === 0 && (A === 1 || C && A <= 0)), R = self.performance.now();
    (v || x || r.stats.parsing.start === 0) && (r.stats.parsing.start = R), a && (A || !S) && (a.stats.parsing.start = R);
    const b = !(y && ((h = r.initSegment) == null ? void 0 : h.url) === ((c = y.initSegment) == null ? void 0 : c.url)), I = new Ba(T, S, u, v, p, b);
    if (!S || T || b) {
      this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part > -1 ? " part: " + l.part : ""} ${this.id === W.MAIN ? "level" : "track"}: ${l.level} id: ${l.id}
        discontinuity: ${T}
        trackSwitch: ${v}
        contiguous: ${S}
        accurateTimeOffset: ${u}
        timeOffset: ${p}
        initSegmentChange: ${b}`);
      const _ = new Na(i, s, e, o, d);
      this.configureTransmuxer(_);
    }
    if (this.frag = r, this.part = a, this.workerContext)
      this.workerContext.worker.postMessage({
        instanceNo: f,
        cmd: "demux",
        data: t,
        decryptdata: m,
        chunkMeta: l,
        state: I
      }, t instanceof ArrayBuffer ? [t] : []);
    else if (g) {
      const _ = g.push(t, m, l, I);
      Qt(_) ? _.then((F) => {
        this.handleTransmuxComplete(F);
      }).catch((F) => {
        this.transmuxerError(F, l, "transmuxer-interface push error");
      }) : this.handleTransmuxComplete(_);
    }
  }
  flush(t) {
    t.transmuxing.start = self.performance.now();
    const {
      instanceNo: e,
      transmuxer: i
    } = this;
    if (this.workerContext)
      this.workerContext.worker.postMessage({
        instanceNo: e,
        cmd: "flush",
        chunkMeta: t
      });
    else if (i) {
      const s = i.flush(t);
      Qt(s) ? s.then((r) => {
        this.handleFlushResult(r, t);
      }).catch((r) => {
        this.transmuxerError(r, t, "transmuxer-interface flush error");
      }) : this.handleFlushResult(s, t);
    }
  }
  transmuxerError(t, e, i) {
    this.hls && (this.error = t, this.hls.trigger(E.ERROR, {
      type: Y.MEDIA_ERROR,
      details: D.FRAG_PARSING_ERROR,
      chunkMeta: e,
      frag: this.frag || void 0,
      part: this.part || void 0,
      fatal: !1,
      error: t,
      err: t,
      reason: i
    }));
  }
  handleFlushResult(t, e) {
    t.forEach((i) => {
      this.handleTransmuxComplete(i);
    }), this.onFlush(e);
  }
  configureTransmuxer(t) {
    const {
      instanceNo: e,
      transmuxer: i
    } = this;
    this.workerContext ? this.workerContext.worker.postMessage({
      instanceNo: e,
      cmd: "configure",
      config: t
    }) : i && i.configure(t);
  }
  handleTransmuxComplete(t) {
    t.chunkMeta.transmuxing.end = self.performance.now(), this.onTransmuxComplete(t);
  }
}
function rr() {
  return self.SourceBuffer || self.WebKitSourceBuffer;
}
function nr() {
  if (!_t())
    return !1;
  const t = rr();
  return !t || t.prototype && typeof t.prototype.appendBuffer == "function" && typeof t.prototype.remove == "function";
}
function po() {
  if (!nr())
    return !1;
  const n = _t();
  return typeof n?.isTypeSupported == "function" && (["avc1.42E01E,mp4a.40.2", "av01.0.01M.08", "vp09.00.50.08"].some((t) => n.isTypeSupported(Xt(t, "video"))) || ["mp4a.40.2", "fLaC"].some((t) => n.isTypeSupported(Xt(t, "audio"))));
}
function Eo() {
  var n;
  const t = rr();
  return typeof (t == null || (n = t.prototype) == null ? void 0 : n.changeType) == "function";
}
const vo = 100;
class yo extends On {
  constructor(t, e, i) {
    super(t, e, i, "stream-controller", W.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, r = s ? s.currentTime : null;
      if (r === null || !B(r) || (this.log(`Media seeked to ${r.toFixed(3)}`), !this.getBufferedFrag(r)))
        return;
      const a = this.getFwdBufferInfoAtPos(s, r, W.MAIN, 0);
      if (a === null || a.len === 0) {
        this.warn(`Main forward buffer length at ${r} on "seeked" event ${a ? a.len : "empty"})`);
        return;
      }
      this.tick();
    }, this.registerListeners();
  }
  registerListeners() {
    super.registerListeners();
    const {
      hls: t
    } = this;
    t.on(E.MANIFEST_PARSED, this.onManifestParsed, this), t.on(E.LEVEL_LOADING, this.onLevelLoading, this), t.on(E.LEVEL_LOADED, this.onLevelLoaded, this), t.on(E.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this), t.on(E.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), t.on(E.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this), t.on(E.BUFFER_CREATED, this.onBufferCreated, this), t.on(E.BUFFER_FLUSHED, this.onBufferFlushed, this), t.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.on(E.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  unregisterListeners() {
    super.unregisterListeners();
    const {
      hls: t
    } = this;
    t.off(E.MANIFEST_PARSED, this.onManifestParsed, this), t.off(E.LEVEL_LOADED, this.onLevelLoaded, this), t.off(E.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this), t.off(E.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this), t.off(E.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this), t.off(E.BUFFER_CREATED, this.onBufferCreated, this), t.off(E.BUFFER_FLUSHED, this.onBufferFlushed, this), t.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), t.off(E.FRAG_BUFFERED, this.onFragBuffered, this);
  }
  onHandlerDestroying() {
    this.onMediaPlaying = this.onMediaSeeked = null, this.unregisterListeners(), super.onHandlerDestroying();
  }
  startLoad(t, e) {
    if (this.levels) {
      const {
        lastCurrentTime: i,
        hls: s
      } = this;
      if (this.stopLoad(), this.setInterval(vo), this.level = -1, !this.startFragRequested) {
        let r = s.startLevel;
        r === -1 && (s.config.testBandwidth && this.levels.length > 1 ? (r = 0, this.bitrateTest = !0) : r = s.firstAutoLevel), s.nextLoadLevel = r, this.level = s.loadLevel, this._hasEnoughToStart = !!e;
      }
      i > 0 && t === -1 && !e && (this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`), t = i), this.state = k.IDLE, this.nextLoadPosition = this.lastCurrentTime = t + this.timelineOffset, this.startPosition = e ? -1 : t, 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: t,
          level: e
        } = this, i = t?.[e], s = 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 t;
    super.onTickEnd(), (t = this.media) != null && t.readyState && this.media.seeking === !1 && (this.lastCurrentTime = this.media.currentTime), this.checkFragmentChanged();
  }
  doTickIdle() {
    const {
      hls: t,
      levelLastLoaded: e,
      levels: i,
      media: s
    } = this;
    if (e === null || !s && !this.primaryPrefetch && (this.startFragRequested || !t.config.startFragPrefetch) || this.altAudio && this.audioOnly)
      return;
    const r = this.buffering ? t.nextLoadLevel : t.loadLevel;
    if (!(i != null && i[r]))
      return;
    const a = i[r], o = this.getMainFwdBufferInfo();
    if (o === null)
      return;
    const u = this.getLevelDetails();
    if (u && this._streamEnded(o, u)) {
      const p = {};
      this.altAudio === 2 && (p.type = "video"), this.hls.trigger(E.BUFFER_EOS, p), this.state = k.ENDED;
      return;
    }
    if (!this.buffering)
      return;
    t.loadLevel !== r && t.manualLevel === -1 && this.log(`Adapting to level ${r} from level ${this.level}`), this.level = t.nextLoadLevel = r;
    const l = a.details;
    if (!l || this.state === k.WAITING_LEVEL || this.waitForLive(a)) {
      this.level = r, 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 c = this.backtrackFragment ? this.backtrackFragment.start : o.end;
    let f = this.getNextFragment(c, l);
    if (this.couldBacktrack && !this.fragPrevious && f && ft(f) && this.fragmentTracker.getState(f) !== lt.OK) {
      var g;
      const m = ((g = this.backtrackFragment) != null ? g : f).sn - l.startSN, y = l.fragments[m - 1];
      y && f.cc === y.cc && (f = y, this.fragmentTracker.removeFragment(y));
    } else this.backtrackFragment && o.len && (this.backtrackFragment = null);
    if (f && this.isLoopLoading(f, c)) {
      if (!f.gap) {
        const m = this.audioOnly && !this.altAudio ? tt.AUDIO : tt.VIDEO, y = (m === tt.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
        y && this.afterBufferFlushed(y, m, W.MAIN);
      }
      f = this.getNextFragmentLoopLoading(f, l, o, W.MAIN, h);
    }
    f && (f.initSegment && !f.initSegment.data && !this.bitrateTest && (f = f.initSegment), this.loadFragment(f, a, c));
  }
  loadFragment(t, e, i) {
    const s = this.fragmentTracker.getState(t);
    s === lt.NOT_LOADED || s === lt.PARTIAL ? ft(t) ? this.bitrateTest ? (this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`), this._loadBitrateTestFrag(t, e)) : super.loadFragment(t, e, i) : this._loadInitSegment(t, e) : this.clearTrackerIfNeeded(t);
  }
  getBufferedFrag(t) {
    return this.fragmentTracker.getBufferedFrag(t, W.MAIN);
  }
  followingBufferedFrag(t) {
    return t ? this.getBufferedFrag(t.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: t,
      media: e
    } = this;
    if (e != null && e.readyState) {
      let i;
      const s = this.getAppendedFrag(e.currentTime);
      s && s.start > 1 && this.flushMainBuffer(0, s.start - 1);
      const r = this.getLevelDetails();
      if (r != null && r.live) {
        const o = this.getMainFwdBufferInfo();
        if (!o || o.len < r.targetduration * 2)
          return;
      }
      if (!e.paused && t) {
        const o = this.hls.nextLoadLevel, u = t[o], l = this.fragLastKbps;
        l && this.fragCurrent ? i = this.fragCurrent.duration * u.maxBitrate / (1e3 * l) + 1 : i = 0;
      } else
        i = 0;
      const a = this.getBufferedFrag(e.currentTime + i);
      if (a) {
        const o = this.followingBufferedFrag(a);
        if (o) {
          this.abortCurrentFrag();
          const u = o.maxStartPTS ? o.maxStartPTS : o.start, l = o.duration, d = Math.max(a.end, u + 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 t = this.fragCurrent;
    switch (this.fragCurrent = null, this.backtrackFragment = null, t && (t.abortRequests(), this.fragmentTracker.removeFragment(t)), 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(t, e) {
    super.flushMainBuffer(t, e, this.altAudio === 2 ? "video" : null);
  }
  onMediaAttached(t, e) {
    super.onMediaAttached(t, e);
    const i = e.media;
    wt(i, "playing", this.onMediaPlaying), wt(i, "seeked", this.onMediaSeeked);
  }
  onMediaDetaching(t, e) {
    const {
      media: i
    } = this;
    i && (Ct(i, "playing", this.onMediaPlaying), Ct(i, "seeked", this.onMediaSeeked)), this.videoBuffer = null, this.fragPlaying = null, super.onMediaDetaching(t, e), !e.transferMedia && (this._hasEnoughToStart = !1);
  }
  onManifestLoading() {
    super.onManifestLoading(), this.log("Trigger BUFFER_RESET"), this.hls.trigger(E.BUFFER_RESET, void 0), this.couldBacktrack = !1, this.fragLastKbps = 0, this.fragPlaying = this.backtrackFragment = null, this.altAudio = 0, this.audioOnly = !1;
  }
  onManifestParsed(t, e) {
    let i = !1, s = !1;
    for (let r = 0; r < e.levels.length; r++) {
      const a = e.levels[r].audioCodec;
      a && (i = i || a.indexOf("mp4a.40.2") !== -1, s = s || a.indexOf("mp4a.40.5") !== -1);
    }
    this.audioCodecSwitch = i && s && !Eo(), this.audioCodecSwitch && this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"), this.levels = e.levels, this.startFragRequested = !1;
  }
  onLevelLoading(t, e) {
    const {
      levels: i
    } = this;
    if (!i || this.state !== k.IDLE)
      return;
    const s = e.levelInfo;
    (!s.details || s.details.live && (this.levelLastLoaded !== s || s.details.expired) || this.waitForCdnTuneIn(s.details)) && (this.state = k.WAITING_LEVEL);
  }
  onLevelLoaded(t, e) {
    var i;
    const {
      levels: s,
      startFragRequested: r
    } = this, a = e.level, o = e.details, u = 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:${u}`);
    const l = e.levelInfo, d = this.fragCurrent;
    d && (this.state === k.FRAG_LOADING || this.state === k.FRAG_LOADING_WAITING_RETRY) && d.level !== e.level && d.loader && this.abortCurrentFrag();
    let h = 0;
    if (o.live || (i = l.details) != null && i.live) {
      var c;
      if (this.checkLiveUpdate(o), o.deltaUpdateFailed)
        return;
      h = this.alignPlaylists(o, l.details, (c = this.levelLastLoaded) == null ? void 0 : c.details);
    }
    if (l.details = o, this.levelLastLoaded = l, r || this.setStartPosition(o, h), this.hls.trigger(E.LEVEL_UPDATED, {
      details: o,
      level: a
    }), this.state === k.WAITING_LEVEL) {
      if (this.waitForCdnTuneIn(o))
        return;
      this.state = k.IDLE;
    }
    r && o.live && this.synchronizeToLiveEdge(o), this.tick();
  }
  synchronizeToLiveEdge(t) {
    const {
      config: e,
      media: i
    } = this;
    if (!i)
      return;
    const s = this.hls.liveSyncPosition, r = this.getLoadPosition(), a = t.fragmentStart, o = t.edge, u = r >= a - e.maxFragLookUpTolerance && r <= o;
    if (s !== null && i.duration > s && (r < s || !u)) {
      const d = e.liveMaxLatencyDuration !== void 0 ? e.liveMaxLatencyDuration : e.liveMaxLatencyDurationCount * t.targetduration;
      if ((!u && i.readyState < 4 || r < o - d) && (this._hasEnoughToStart || (this.nextLoadPosition = s), i.readyState))
        if (this.warn(`Playback: ${r.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 = q.bufferInfo(i, s, 0);
          if (!((l = h.buffered) != null && l.length)) {
            i.currentTime = s;
            return;
          }
          if (h.start <= r) {
            i.currentTime = s;
            return;
          }
          const {
            nextStart: f
          } = q.bufferedInfo(h.buffered, r, 0);
          f && (i.currentTime = f);
        } else
          i.currentTime = s;
    }
  }
  _handleFragmentLoadProgress(t) {
    var e;
    const i = t.frag, {
      part: s,
      payload: r
    } = t, {
      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 u = o.details;
    if (!u) {
      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 = u.PTSKnown || !u.live, h = (e = i.initSegment) == null ? void 0 : e.data, c = this._getAudioCodec(o), f = this.transmuxer = this.transmuxer || new mo(this.hls, W.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this)), g = s ? s.index : -1, p = g !== -1, m = new Ms(i.level, i.sn, i.stats.chunkCount, r.byteLength, g, p), y = this.initPTS[i.cc];
    f.push(r, h, c, l, i, s, u.totalduration, d, m, y);
  }
  onAudioTrackSwitching(t, e) {
    const i = this.hls, s = this.altAudio === 2;
    if (vi(e.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(E.BUFFER_FLUSHED, () => {
          this.hls && this.hls.trigger(E.AUDIO_TRACK_SWITCHED, e);
        }), i.trigger(E.BUFFER_FLUSHING, {
          startOffset: 0,
          endOffset: Number.POSITIVE_INFINITY,
          type: null
        });
        return;
      }
      i.trigger(E.AUDIO_TRACK_SWITCHED, e);
    }
  }
  onAudioTrackSwitched(t, e) {
    const i = vi(e.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(t, e) {
    const i = e.tracks;
    let s, r, a = !1;
    for (const o in i) {
      const u = i[o];
      if (u.id === "main") {
        if (r = o, s = u, o === "video") {
          const l = i[o];
          l && (this.videoBuffer = l.buffer);
        }
      } else
        a = !0;
    }
    a && s ? (this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`), this.mediaBuffer = s.buffer) : this.mediaBuffer = this.media;
  }
  onFragBuffered(t, e) {
    const {
      frag: i,
      part: s
    } = e, r = i.type === W.MAIN;
    if (r) {
      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)), ft(i) && (this.fragPrevious = i), this.fragBufferedComplete(i, s);
    }
    const a = this.media;
    a && (!this._hasEnoughToStart && q.getBuffered(a).length && (this._hasEnoughToStart = !0, this.seekToStartPos()), r && this.tick());
  }
  get hasEnoughToStart() {
    return this._hasEnoughToStart;
  }
  onError(t, e) {
    var i;
    if (e.fatal) {
      this.state = k.ERROR;
      return;
    }
    switch (e.details) {
      case D.FRAG_GAP:
      case D.FRAG_PARSING_ERROR:
      case D.FRAG_DECRYPT_ERROR:
      case D.FRAG_LOAD_ERROR:
      case D.FRAG_LOAD_TIMEOUT:
      case D.KEY_LOAD_ERROR:
      case D.KEY_LOAD_TIMEOUT:
        this.onFragmentOrKeyLoadError(W.MAIN, e);
        break;
      case D.LEVEL_LOAD_ERROR:
      case D.LEVEL_LOAD_TIMEOUT:
      case D.LEVEL_PARSING_ERROR:
        !e.levelRetry && this.state === k.WAITING_LEVEL && ((i = e.context) == null ? void 0 : i.type) === X.LEVEL && (this.state = k.IDLE);
        break;
      case D.BUFFER_ADD_CODEC_ERROR:
      case D.BUFFER_APPEND_ERROR:
        if (e.parent !== "main")
          return;
        this.reduceLengthAndFlushBuffer(e) && this.resetLoadingState();
        break;
      case D.BUFFER_FULL_ERROR:
        if (e.parent !== "main")
          return;
        this.reduceLengthAndFlushBuffer(e) && (!this.config.interstitialsController && this.config.assetPlayerId ? this._hasEnoughToStart = !0 : this.flushMainBuffer(0, Number.POSITIVE_INFINITY));
        break;
      case D.INTERNAL_EXCEPTION:
        this.recoverWorkerError(e);
        break;
    }
  }
  onFragLoadEmergencyAborted() {
    this.state = k.IDLE, this._hasEnoughToStart || (this.startFragRequested = !1, this.nextLoadPosition = this.lastCurrentTime), this.tickImmediate();
  }
  onBufferFlushed(t, {
    type: e
  }) {
    if (e !== tt.AUDIO || !this.altAudio) {
      const i = (e === tt.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
      i && (this.afterBufferFlushed(i, e, W.MAIN), this.tick());
    }
  }
  onLevelsUpdated(t, e) {
    this.level > -1 && this.fragCurrent && (this.level = this.fragCurrent.level, this.level === -1 && this.resetWhenMissingContext(this.fragCurrent)), this.levels = e.levels;
  }
  swapAudioCodec() {
    this.audioCodecSwap = !this.audioCodecSwap;
  }
  /**
   * Seeks to the set startPosition if not equal to the mediaElement's current time.
   */
  seekToStartPos() {
    const {
      media: t
    } = this;
    if (!t)
      return;
    const e = t.currentTime;
    let i = this.startPosition;
    if (i >= 0 && e < i) {
      if (t.seeking) {
        this.log(`could not seek to ${i}, already seeking at ${e}`);
        return;
      }
      const s = this.timelineOffset;
      s && i && (i += s);
      const r = this.getLevelDetails(), a = q.getBuffered(t), o = a.length ? a.start(0) : 0, u = o - i, l = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
      (this.config.startOnSegmentBoundary || u > 0 && (u < l || this.loadingParts && u < 2 * (r?.partTarget || 0))) && (this.log(`adjusting start position by ${u} to match buffer start`), i += u, this.startPosition = i), e < i && (this.log(`seek to target start position ${i} from current time ${e} buffer start ${o}`), t.currentTime = i);
    }
  }
  _getAudioCodec(t) {
    let e = this.config.defaultAudioCodec || t.audioCodec;
    return this.audioCodecSwap && e && (this.log("Swapping audio codec"), e.indexOf("mp4a.40.5") !== -1 ? e = "mp4a.40.2" : e = "mp4a.40.5"), e;
  }
  _loadBitrateTestFrag(t, e) {
    t.bitrateTest = !0, this._doFragLoad(t, e).then((i) => {
      const {
        hls: s
      } = this, r = i?.frag;
      if (!r || this.fragContextChanged(r))
        return;
      e.fragmentError = 0, this.state = k.IDLE, this.startFragRequested = !1, this.bitrateTest = !1;
      const a = r.stats;
      a.parsing.start = a.parsing.end = a.buffering.start = a.buffering.end = self.performance.now(), s.trigger(E.FRAG_LOADED, i), r.bitrateTest = !1;
    }).catch((i) => {
      this.state === k.STOPPED || this.state === k.ERROR || (this.warn(i), this.resetFragmentLoading(t));
    });
  }
  _handleTransmuxComplete(t) {
    const e = this.playlistType, {
      hls: i
    } = this, {
      remuxResult: s,
      chunkMeta: r
    } = t, a = this.getCurrentContext(r);
    if (!a) {
      this.resetWhenMissingContext(r);
      return;
    }
    const {
      frag: o,
      part: u,
      level: l
    } = a, {
      video: d,
      text: h,
      id3: c,
      initSegment: f
    } = s, {
      details: g
    } = l, p = this.altAudio ? void 0 : s.audio;
    if (this.fragContextChanged(o)) {
      this.fragmentTracker.removeFragment(o);
      return;
    }
    if (this.state = k.PARSING, f) {
      const m = f.tracks;
      if (m) {
        const x = o.initSegment || o;
        if (this.unhandledEncryptionError(f, o))
          return;
        this._bufferInitSegment(l, m, x, r), i.trigger(E.FRAG_PARSING_INIT_SEGMENT, {
          frag: x,
          id: e,
          tracks: m
        });
      }
      const y = f.initPTS, T = f.timescale, v = this.initPTS[o.cc];
      if (B(y) && (!v || v.baseTime !== y || v.timescale !== T)) {
        const x = f.trackId;
        this.initPTS[o.cc] = {
          baseTime: y,
          timescale: T,
          trackId: x
        }, i.trigger(E.INIT_PTS_FOUND, {
          frag: o,
          id: e,
          initPTS: y,
          timescale: T,
          trackId: x
        });
      }
    }
    if (d && g) {
      p && d.type === "audiovideo" && this.logMuxedErr(o);
      const m = g.fragments[o.sn - 1 - g.startSN], y = o.sn === g.startSN, T = !m || o.cc > m.cc;
      if (s.independent !== !1) {
        const {
          startPTS: v,
          endPTS: x,
          startDTS: A,
          endDTS: C
        } = d;
        if (u)
          u.elementaryStreams[d.type] = {
            startPTS: v,
            endPTS: x,
            startDTS: A,
            endDTS: C
          };
        else if (d.firstKeyFrame && d.independent && r.id === 1 && !T && (this.couldBacktrack = !0), d.dropped && d.independent) {
          const S = this.getMainFwdBufferInfo(), R = (S ? S.end : this.getLoadPosition()) + this.config.maxBufferHole, b = d.firstKeyFramePTS ? d.firstKeyFramePTS : v;
          if (!y && R < b - this.config.maxBufferHole && !T) {
            this.backtrack(o);
            return;
          } else T && (o.gap = !0);
          o.setElementaryStreamInfo(d.type, o.start, x, o.start, C, !0);
        } else y && v - (g.appliedTimelineOffset || 0) > de && (o.gap = !0);
        o.setElementaryStreamInfo(d.type, v, x, A, C), this.backtrackFragment && (this.backtrackFragment = o), this.bufferFragmentData(d, o, u, r, y || T);
      } else if (y || T)
        o.gap = !0;
      else {
        this.backtrack(o);
        return;
      }
    }
    if (p) {
      const {
        startPTS: m,
        endPTS: y,
        startDTS: T,
        endDTS: v
      } = p;
      u && (u.elementaryStreams[tt.AUDIO] = {
        startPTS: m,
        endPTS: y,
        startDTS: T,
        endDTS: v
      }), o.setElementaryStreamInfo(tt.AUDIO, m, y, T, v), this.bufferFragmentData(p, o, u, r);
    }
    if (g && c != null && c.samples.length) {
      const m = {
        id: e,
        frag: o,
        details: g,
        samples: c.samples
      };
      i.trigger(E.FRAG_PARSING_METADATA, m);
    }
    if (g && h) {
      const m = {
        id: e,
        frag: o,
        details: g,
        samples: h.samples
      };
      i.trigger(E.FRAG_PARSING_USERDATA, m);
    }
  }
  logMuxedErr(t) {
    this.warn(`${ft(t) ? "Media" : "Init"} segment with muxed audiovideo where only video expected: ${t.url}`);
  }
  _bufferInitSegment(t, e, i, s) {
    if (this.state !== k.PARSING)
      return;
    this.audioOnly = !!e.audio && !e.video, this.altAudio && !this.audioOnly && (delete e.audio, e.audiovideo && this.logMuxedErr(i));
    const {
      audio: r,
      video: a,
      audiovideo: o
    } = e;
    if (r) {
      const l = t.audioCodec;
      let d = le(r.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 c = r.metadata;
        c && "channelCount" in c && (c.channelCount || 1) !== 1 && h.indexOf("firefox") === -1 && (d = "mp4a.40.5");
      }
      d && d.indexOf("mp4a.40.5") !== -1 && h.indexOf("android") !== -1 && r.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}"`), r.levelCodec = d, r.id = W.MAIN, this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${d || ""}/${l || ""}/${r.codec}]`), delete e.audiovideo;
    }
    if (a) {
      a.levelCodec = t.videoCodec, a.id = W.MAIN;
      const l = a.codec;
      if (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]=[${t.videoCodec || ""}/${l}]${a.codec !== l ? " parsed-corrected=" + a.codec : ""}${a.supplemental ? " supplemental=" + a.supplemental : ""}`), delete e.audiovideo;
    }
    o && (this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`), delete e.video, delete e.audio);
    const u = Object.keys(e);
    if (u.length) {
      if (this.hls.trigger(E.BUFFER_CODECS, e), !this.hls)
        return;
      u.forEach((l) => {
        const h = e[l].initSegment;
        h != null && h.byteLength && this.hls.trigger(E.BUFFER_APPENDING, {
          type: l,
          data: h,
          frag: i,
          part: null,
          chunkMeta: s,
          parent: i.type
        });
      });
    }
    this.tickImmediate();
  }
  getMainFwdBufferInfo() {
    const t = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
    return this.getFwdBufferInfo(t, W.MAIN);
  }
  get maxBufferLength() {
    const {
      levels: t,
      level: e
    } = this, i = t?.[e];
    return i ? this.getMaxBufferLength(i.maxBitrate) : this.config.maxBufferLength;
  }
  backtrack(t) {
    this.couldBacktrack = !0, this.backtrackFragment = t, this.resetTransmuxer(), this.flushBufferGap(t), this.fragmentTracker.removeFragment(t), this.fragPrevious = null, this.nextLoadPosition = t.start, this.state = k.IDLE;
  }
  checkFragmentChanged() {
    const t = this.media;
    let e = null;
    if (t && t.readyState > 1 && t.seeking === !1) {
      const i = t.currentTime;
      if (q.isBuffered(t, i) ? e = this.getAppendedFrag(i) : q.isBuffered(t, i + 0.1) && (e = this.getAppendedFrag(i + 0.1)), e) {
        this.backtrackFragment = null;
        const s = this.fragPlaying, r = e.level;
        (!s || e.sn !== s.sn || s.level !== r) && (this.fragPlaying = e, this.hls.trigger(E.FRAG_CHANGED, {
          frag: e
        }), (!s || s.level !== r) && this.hls.trigger(E.LEVEL_SWITCHED, {
          level: r
        }));
      }
    }
  }
  get nextLevel() {
    const t = this.nextBufferedFrag;
    return t ? t.level : -1;
  }
  get currentFrag() {
    var t;
    if (this.fragPlaying)
      return this.fragPlaying;
    const e = ((t = this.media) == null ? void 0 : t.currentTime) || this.lastCurrentTime;
    return B(e) ? this.getAppendedFrag(e) : null;
  }
  get currentProgramDateTime() {
    var t;
    const e = ((t = this.media) == null ? void 0 : t.currentTime) || this.lastCurrentTime;
    if (B(e)) {
      const i = this.getLevelDetails(), s = this.currentFrag || (i ? Ze(null, i.fragments, e) : null);
      if (s) {
        const r = s.programDateTime;
        if (r !== null) {
          const a = r + (e - s.start) * 1e3;
          return new Date(a);
        }
      }
    }
    return null;
  }
  get currentLevel() {
    const t = this.currentFrag;
    return t ? t.level : -1;
  }
  get nextBufferedFrag() {
    const t = this.currentFrag;
    return t ? this.followingBufferedFrag(t) : null;
  }
  get forceStartLoad() {
    return this._forceStartLoad;
  }
}
class To extends Rt {
  constructor(t, e) {
    super("key-loader", e), this.config = void 0, this.keyIdToKeyInfo = {}, this.emeController = null, this.config = t;
  }
  abort(t) {
    for (const i in this.keyIdToKeyInfo) {
      const s = this.keyIdToKeyInfo[i].loader;
      if (s) {
        var e;
        if (t && t !== ((e = s.context) == null ? void 0 : e.frag.type))
          return;
        s.abort();
      }
    }
  }
  detach() {
    for (const t in this.keyIdToKeyInfo) {
      const e = this.keyIdToKeyInfo[t];
      (e.mediaKeySessionContext || e.decryptdata.isCommonEncryption) && delete this.keyIdToKeyInfo[t];
    }
  }
  destroy() {
    this.detach();
    for (const t in this.keyIdToKeyInfo) {
      const e = this.keyIdToKeyInfo[t].loader;
      e && e.destroy();
    }
    this.keyIdToKeyInfo = {};
  }
  createKeyLoadError(t, e = D.KEY_LOAD_ERROR, i, s, r) {
    return new Lt({
      type: Y.NETWORK_ERROR,
      details: e,
      fatal: !1,
      frag: t,
      response: r,
      error: i,
      networkDetails: s
    });
  }
  loadClear(t, e, i) {
    return null;
  }
  load(t) {
    return !t.decryptdata && t.encrypted && this.emeController && this.config.emeEnabled ? this.emeController.selectKeySystemFormat(t).then((e) => this.loadInternal(t, e)) : this.loadInternal(t);
  }
  loadInternal(t, e) {
    var i, s;
    const r = t.decryptdata;
    if (!r) {
      const l = new Error(e ? `Expected frag.decryptdata to be defined after setting format ${e}` : `Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController && this.config.emeEnabled})`);
      return Promise.reject(this.createKeyLoadError(t, D.KEY_LOAD_ERROR, l));
    }
    const a = r.uri;
    if (!a)
      return Promise.reject(this.createKeyLoadError(t, D.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${a}"`)));
    const o = Me(r);
    let u = this.keyIdToKeyInfo[o];
    if ((i = u) != null && i.decryptdata.key)
      return r.key = u.decryptdata.key, Promise.resolve({
        frag: t,
        keyInfo: u
      });
    if (this.emeController && (s = u) != null && s.keyLoadPromise)
      switch (this.emeController.getKeyStatus(u.decryptdata)) {
        case "usable":
        case "usable-in-future":
          return u.keyLoadPromise.then((d) => {
            const {
              keyInfo: h
            } = d;
            return r.key = h.decryptdata.key, {
              frag: t,
              keyInfo: h
            };
          });
      }
    switch (this.log(`${this.keyIdToKeyInfo[o] ? "Rel" : "L"}oading${r.keyId ? " keyId: " + qt(r.keyId) : ""} URI: ${r.uri} from ${t.type} ${t.level}`), u = this.keyIdToKeyInfo[o] = {
      decryptdata: r,
      keyLoadPromise: null,
      loader: null,
      mediaKeySessionContext: null
    }, r.method) {
      case "SAMPLE-AES":
      case "SAMPLE-AES-CENC":
      case "SAMPLE-AES-CTR":
        return r.keyFormat === "identity" ? this.loadKeyHTTP(u, t) : this.loadKeyEME(u, t);
      case "AES-128":
      case "AES-256":
      case "AES-256-CTR":
        return this.loadKeyHTTP(u, t);
      default:
        return Promise.reject(this.createKeyLoadError(t, D.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${r.method}"`)));
    }
  }
  loadKeyEME(t, e) {
    const i = {
      frag: e,
      keyInfo: t
    };
    if (this.emeController && this.config.emeEnabled) {
      var s;
      if (!t.decryptdata.keyId && (s = e.initSegment) != null && s.data) {
        const a = Cr(e.initSegment.data);
        if (a.length) {
          const o = a[0];
          o.some((u) => u !== 0) && (this.log(`Using keyId found in init segment ${qt(o)}`), t.decryptdata.keyId = o, ye.setKeyIdForUri(t.decryptdata.uri, o));
        }
      }
      const r = this.emeController.loadKey(i);
      return (t.keyLoadPromise = r.then((a) => (t.mediaKeySessionContext = a, i))).catch((a) => {
        throw t.keyLoadPromise = null, "data" in a && (a.data.frag = e), a;
      });
    }
    return Promise.resolve(i);
  }
  loadKeyHTTP(t, e) {
    const i = this.config, s = i.loader, r = new s(i);
    return e.keyLoader = t.loader = r, t.keyLoadPromise = new Promise((a, o) => {
      const u = {
        keyInfo: t,
        frag: e,
        responseType: "arraybuffer",
        url: t.decryptdata.uri
      }, l = i.keyLoadPolicy.default, d = {
        loadPolicy: l,
        timeout: l.maxLoadTimeMs,
        maxRetry: 0,
        retryDelay: 0,
        maxRetryDelay: 0
      }, h = {
        onSuccess: (c, f, g, p) => {
          const {
            frag: m,
            keyInfo: y
          } = g, T = Me(y.decryptdata);
          if (!m.decryptdata || y !== this.keyIdToKeyInfo[T])
            return o(this.createKeyLoadError(m, D.KEY_LOAD_ERROR, new Error("after key load, decryptdata unset or changed"), p));
          y.decryptdata.key = m.decryptdata.key = new Uint8Array(c.data), m.keyLoader = null, y.loader = null, a({
            frag: m,
            keyInfo: y
          });
        },
        onError: (c, f, g, p) => {
          this.resetLoader(f), o(this.createKeyLoadError(e, D.KEY_LOAD_ERROR, new Error(`HTTP Error ${c.code} loading key ${c.text}`), g, ct({
            url: u.url,
            data: void 0
          }, c)));
        },
        onTimeout: (c, f, g) => {
          this.resetLoader(f), o(this.createKeyLoadError(e, D.KEY_LOAD_TIMEOUT, new Error("key loading timed out"), g));
        },
        onAbort: (c, f, g) => {
          this.resetLoader(f), o(this.createKeyLoadError(e, D.INTERNAL_ABORTED, new Error("key loading aborted"), g));
        }
      };
      r.load(u, d, h);
    });
  }
  resetLoader(t) {
    const {
      frag: e,
      keyInfo: i,
      url: s
    } = t, r = i.loader;
    e.keyLoader === r && (e.keyLoader = null, i.loader = null);
    const a = Me(i.decryptdata) || s;
    delete this.keyIdToKeyInfo[a], r && r.destroy();
  }
}
function Me(n) {
  return n.uri;
}
function os(n) {
  const {
    type: t
  } = n;
  switch (t) {
    case X.AUDIO_TRACK:
      return W.AUDIO;
    case X.SUBTITLE_TRACK:
      return W.SUBTITLE;
    default:
      return W.MAIN;
  }
}
function Ne(n, t) {
  let e = n.url;
  return (e === void 0 || e.indexOf("data:") === 0) && (e = t.url), e;
}
class xo {
  constructor(t) {
    this.hls = void 0, this.loaders = /* @__PURE__ */ Object.create(null), this.variableList = null, this.onManifestLoaded = this.checkAutostartLoad, this.hls = t, this.registerListeners();
  }
  startLoad(t) {
  }
  stopLoad() {
    this.destroyInternalLoaders();
  }
  registerListeners() {
    const {
      hls: t
    } = this;
    t.on(E.MANIFEST_LOADING, this.onManifestLoading, this), t.on(E.LEVEL_LOADING, this.onLevelLoading, this), t.on(E.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this), t.on(E.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this), t.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  unregisterListeners() {
    const {
      hls: t
    } = this;
    t.off(E.MANIFEST_LOADING, this.onManifestLoading, this), t.off(E.LEVEL_LOADING, this.onLevelLoading, this), t.off(E.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this), t.off(E.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this), t.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this);
  }
  /**
   * Returns defaults or configured loader-type overloads (pLoader and loader config params)
   */
  createInternalLoader(t) {
    const e = this.hls.config, i = e.pLoader, s = e.loader, r = i || s, a = new r(e);
    return this.loaders[t.type] = a, a;
  }
  getInternalLoader(t) {
    return this.loaders[t.type];
  }
  resetInternalLoader(t) {
    this.loaders[t] && delete this.loaders[t];
  }
  /**
   * Call `destroy` on all internal loader instances mapped (one per context type)
   */
  destroyInternalLoaders() {
    for (const t in this.loaders) {
      const e = this.loaders[t];
      e && e.destroy(), this.resetInternalLoader(t);
    }
  }
  destroy() {
    this.variableList = null, this.unregisterListeners(), this.destroyInternalLoaders();
  }
  onManifestLoading(t, e) {
    const {
      url: i
    } = e;
    this.variableList = null, this.load({
      id: null,
      level: 0,
      responseType: "text",
      type: X.MANIFEST,
      url: i,
      deliveryDirectives: null,
      levelOrTrack: null
    });
  }
  onLevelLoading(t, e) {
    const {
      id: i,
      level: s,
      pathwayId: r,
      url: a,
      deliveryDirectives: o,
      levelInfo: u
    } = e;
    this.load({
      id: i,
      level: s,
      pathwayId: r,
      responseType: "text",
      type: X.LEVEL,
      url: a,
      deliveryDirectives: o,
      levelOrTrack: u
    });
  }
  onAudioTrackLoading(t, e) {
    const {
      id: i,
      groupId: s,
      url: r,
      deliveryDirectives: a,
      track: o
    } = e;
    this.load({
      id: i,
      groupId: s,
      level: null,
      responseType: "text",
      type: X.AUDIO_TRACK,
      url: r,
      deliveryDirectives: a,
      levelOrTrack: o
    });
  }
  onSubtitleTrackLoading(t, e) {
    const {
      id: i,
      groupId: s,
      url: r,
      deliveryDirectives: a,
      track: o
    } = e;
    this.load({
      id: i,
      groupId: s,
      level: null,
      responseType: "text",
      type: X.SUBTITLE_TRACK,
      url: r,
      deliveryDirectives: a,
      levelOrTrack: o
    });
  }
  onLevelsUpdated(t, e) {
    const i = this.loaders[X.LEVEL];
    if (i) {
      const s = i.context;
      s && !e.levels.some((r) => r === s.levelOrTrack) && (i.abort(), delete this.loaders[X.LEVEL]);
    }
  }
  load(t) {
    var e;
    const i = this.hls.config;
    let s = this.getInternalLoader(t);
    if (s) {
      const l = this.hls.logger, d = s.context;
      if (d && d.levelOrTrack === t.levelOrTrack && (d.url === t.url || d.deliveryDirectives && !t.deliveryDirectives)) {
        d.url === t.url ? l.log(`[playlist-loader]: ignore ${t.url} ongoing request`) : l.log(`[playlist-loader]: ignore ${t.url} in favor of ${d.url}`);
        return;
      }
      l.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`), s.abort();
    }
    let r;
    if (t.type === X.MANIFEST ? r = i.manifestLoadPolicy.default : r = nt({}, i.playlistLoadPolicy.default, {
      timeoutRetry: null,
      errorRetry: null
    }), s = this.createInternalLoader(t), B((e = t.deliveryDirectives) == null ? void 0 : e.part)) {
      let l;
      if (t.type === X.LEVEL && t.level !== null ? l = this.hls.levels[t.level].details : t.type === X.AUDIO_TRACK && t.id !== null ? l = this.hls.audioTracks[t.id].details : t.type === X.SUBTITLE_TRACK && t.id !== null && (l = this.hls.subtitleTracks[t.id].details), l) {
        const d = l.partTarget, h = l.targetduration;
        if (d && h) {
          const c = Math.max(d * 3, h * 0.8) * 1e3;
          r = nt({}, r, {
            maxTimeToFirstByteMs: Math.min(c, r.maxTimeToFirstByteMs),
            maxLoadTimeMs: Math.min(c, r.maxTimeToFirstByteMs)
          });
        }
      }
    }
    const a = r.errorRetry || r.timeoutRetry || {}, o = {
      loadPolicy: r,
      timeout: r.maxLoadTimeMs,
      maxRetry: a.maxNumRetry || 0,
      retryDelay: a.retryDelayMs || 0,
      maxRetryDelay: a.maxRetryDelayMs || 0
    }, u = {
      onSuccess: (l, d, h, c) => {
        const f = this.getInternalLoader(h);
        this.resetInternalLoader(h.type);
        const g = l.data;
        d.parsing.start = performance.now(), Tt.isMediaPlaylist(g) || h.type !== X.MANIFEST ? this.handleTrackOrLevelPlaylist(l, d, h, c || null, f) : this.handleMasterPlaylist(l, d, h, c);
      },
      onError: (l, d, h, c) => {
        this.handleNetworkError(d, h, !1, l, c);
      },
      onTimeout: (l, d, h) => {
        this.handleNetworkError(d, h, !0, void 0, l);
      }
    };
    s.load(t, o, u);
  }
  checkAutostartLoad() {
    if (!this.hls)
      return;
    const {
      config: {
        autoStartLoad: t,
        startPosition: e
      },
      forceStartLoad: i
    } = this.hls;
    (t || i) && (this.hls.logger.log(`${t ? "auto" : "force"} startLoad with configured startPosition ${e}`), this.hls.startLoad(e));
  }
  handleMasterPlaylist(t, e, i, s) {
    const r = this.hls, a = t.data, o = Ne(t, i), u = Tt.parseMasterPlaylist(a, o);
    if (u.playlistParsingError) {
      e.parsing.end = performance.now(), this.handleManifestParsingError(t, i, u.playlistParsingError, s, e);
      return;
    }
    const {
      contentSteering: l,
      levels: d,
      sessionData: h,
      sessionKeys: c,
      startTimeOffset: f,
      variableList: g
    } = u;
    this.variableList = g, d.forEach((T) => {
      const {
        unknownCodecs: v
      } = T;
      if (v) {
        const {
          preferManagedMediaSource: x
        } = this.hls.config;
        let {
          audioCodec: A,
          videoCodec: C
        } = T;
        for (let S = v.length; S--; ) {
          const R = v[S];
          zt(R, "audio", x) ? (T.audioCodec = A = A ? `${A},${R}` : R, Gt.audio[A.substring(0, 4)] = 2, v.splice(S, 1)) : zt(R, "video", x) && (T.videoCodec = C = C ? `${C},${R}` : R, Gt.video[C.substring(0, 4)] = 2, v.splice(S, 1));
        }
      }
    });
    const {
      AUDIO: p = [],
      SUBTITLES: m,
      "CLOSED-CAPTIONS": y
    } = Tt.parseMasterPlaylistMedia(a, o, u);
    p.length && !p.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"), p.unshift({
      type: "main",
      name: "main",
      groupId: "main",
      default: !1,
      autoselect: !1,
      forced: !1,
      id: -1,
      attrs: new it({}),
      bitrate: 0,
      url: ""
    })), r.trigger(E.MANIFEST_LOADED, {
      levels: d,
      audioTracks: p,
      subtitles: m,
      captions: y,
      contentSteering: l,
      url: o,
      stats: e,
      networkDetails: s,
      sessionData: h,
      sessionKeys: c,
      startTimeOffset: f,
      variableList: g
    });
  }
  handleTrackOrLevelPlaylist(t, e, i, s, r) {
    const a = this.hls, {
      id: o,
      level: u,
      type: l
    } = i, d = Ne(t, i), h = B(u) ? u : B(o) ? o : 0, c = os(i), f = Tt.parseLevelPlaylist(t.data, d, h, c, 0, this.variableList);
    if (l === X.MANIFEST) {
      const g = {
        attrs: new it({}),
        bitrate: 0,
        details: f,
        name: "",
        url: d
      };
      f.requestScheduled = e.loading.start + Ps(f, 0), a.trigger(E.MANIFEST_LOADED, {
        levels: [g],
        audioTracks: [],
        url: d,
        stats: e,
        networkDetails: s,
        sessionData: null,
        sessionKeys: null,
        contentSteering: null,
        startTimeOffset: null,
        variableList: null
      });
    }
    e.parsing.end = performance.now(), i.levelDetails = f, this.handlePlaylistLoaded(f, t, e, i, s, r);
  }
  handleManifestParsingError(t, e, i, s, r) {
    this.hls.trigger(E.ERROR, {
      type: Y.NETWORK_ERROR,
      details: D.MANIFEST_PARSING_ERROR,
      fatal: e.type === X.MANIFEST,
      url: t.url,
      err: i,
      error: i,
      reason: i.message,
      response: t,
      context: e,
      networkDetails: s,
      stats: r
    });
  }
  handleNetworkError(t, e, i = !1, s, r) {
    let a = `A network ${i ? "timeout" : "error" + (s ? " (status " + s.code + ")" : "")} occurred while loading ${t.type}`;
    t.type === X.LEVEL ? a += `: ${t.level} id: ${t.id}` : (t.type === X.AUDIO_TRACK || t.type === X.SUBTITLE_TRACK) && (a += ` id: ${t.id} group-id: "${t.groupId}"`);
    const o = new Error(a);
    this.hls.logger.warn(`[playlist-loader]: ${a}`);
    let u = D.UNKNOWN, l = !1;
    const d = this.getInternalLoader(t);
    switch (t.type) {
      case X.MANIFEST:
        u = i ? D.MANIFEST_LOAD_TIMEOUT : D.MANIFEST_LOAD_ERROR, l = !0;
        break;
      case X.LEVEL:
        u = i ? D.LEVEL_LOAD_TIMEOUT : D.LEVEL_LOAD_ERROR, l = !1;
        break;
      case X.AUDIO_TRACK:
        u = i ? D.AUDIO_TRACK_LOAD_TIMEOUT : D.AUDIO_TRACK_LOAD_ERROR, l = !1;
        break;
      case X.SUBTITLE_TRACK:
        u = i ? D.SUBTITLE_TRACK_LOAD_TIMEOUT : D.SUBTITLE_LOAD_ERROR, l = !1;
        break;
    }
    d && this.resetInternalLoader(t.type);
    const h = {
      type: Y.NETWORK_ERROR,
      details: u,
      fatal: l,
      url: t.url,
      loader: d,
      context: t,
      error: o,
      networkDetails: e,
      stats: r
    };
    if (s) {
      const c = e?.url || t.url;
      h.response = ct({
        url: c,
        data: void 0
      }, s);
    }
    this.hls.trigger(E.ERROR, h);
  }
  handlePlaylistLoaded(t, e, i, s, r, a) {
    const o = this.hls, {
      type: u,
      level: l,
      levelOrTrack: d,
      id: h,
      groupId: c,
      deliveryDirectives: f
    } = s, g = Ne(e, s), p = os(s);
    let m = typeof s.level == "number" && p === W.MAIN ? l : void 0;
    const y = t.playlistParsingError;
    if (y) {
      if (this.hls.logger.warn(`${y} ${t.url}`), !o.config.ignorePlaylistParsingErrors) {
        o.trigger(E.ERROR, {
          type: Y.NETWORK_ERROR,
          details: D.LEVEL_PARSING_ERROR,
          fatal: !1,
          url: g,
          error: y,
          reason: y.message,
          response: e,
          context: s,
          level: m,
          parent: p,
          networkDetails: r,
          stats: i
        });
        return;
      }
      t.playlistParsingError = null;
    }
    if (!t.fragments.length) {
      const T = t.playlistParsingError = new Error("No Segments found in Playlist");
      o.trigger(E.ERROR, {
        type: Y.NETWORK_ERROR,
        details: D.LEVEL_EMPTY_ERROR,
        fatal: !1,
        url: g,
        error: T,
        reason: T.message,
        response: e,
        context: s,
        level: m,
        parent: p,
        networkDetails: r,
        stats: i
      });
      return;
    }
    switch (t.live && a && (a.getCacheAge && (t.ageHeader = a.getCacheAge() || 0), (!a.getCacheAge || isNaN(t.ageHeader)) && (t.ageHeader = 0)), u) {
      case X.MANIFEST:
      case X.LEVEL:
        if (m) {
          if (!d)
            m = 0;
          else if (d !== o.levels[m]) {
            const T = o.levels.indexOf(d);
            T > -1 && (m = T);
          }
        }
        o.trigger(E.LEVEL_LOADED, {
          details: t,
          levelInfo: d || o.levels[0],
          level: m || 0,
          id: h || 0,
          stats: i,
          networkDetails: r,
          deliveryDirectives: f,
          withoutMultiVariant: u === X.MANIFEST
        });
        break;
      case X.AUDIO_TRACK:
        o.trigger(E.AUDIO_TRACK_LOADED, {
          details: t,
          track: d,
          id: h || 0,
          groupId: c || "",
          stats: i,
          networkDetails: r,
          deliveryDirectives: f
        });
        break;
      case X.SUBTITLE_TRACK:
        o.trigger(E.SUBTITLE_TRACK_LOADED, {
          details: t,
          track: d,
          id: h || 0,
          groupId: c || "",
          stats: i,
          networkDetails: r,
          deliveryDirectives: f
        });
        break;
    }
  }
}
const So = {
  supported: !0,
  powerEfficient: !0,
  smooth: !0
  // keySystemAccess: null,
}, Lo = {
  supported: !1,
  smooth: !1,
  powerEfficient: !1
  // keySystemAccess: null,
}, Ao = {
  supported: !0,
  configurations: [],
  decodingInfoResults: [So]
};
function Ro(n, t) {
  return {
    supported: !1,
    configurations: t,
    decodingInfoResults: [Lo],
    error: n
  };
}
function bo(n, t, e, i = {}) {
  const s = n.videoCodec;
  if (!s && !n.audioCodec || !e)
    return Promise.resolve(Ao);
  const r = [], a = Io(n), o = a.length, u = Do(n, t, o > 0), l = u.length;
  for (let d = o || 1 * l || 1; d--; ) {
    const h = {
      type: "media-source"
    };
    if (o && (h.video = a[d % o]), l) {
      h.audio = u[d % l];
      const c = h.audio.bitrate;
      h.video && c && (h.video.bitrate -= c);
    }
    r.push(h);
  }
  if (s) {
    const d = navigator.userAgent;
    if (s.split(",").some((h) => ze(h)) && ys())
      return Promise.resolve(Ro(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`), r));
  }
  return Promise.all(r.map((d) => {
    const h = _o(d);
    return i[h] || (i[h] = e.decodingInfo(d));
  })).then((d) => ({
    supported: !d.some((h) => !h.supported),
    configurations: r,
    decodingInfoResults: d
  })).catch((d) => ({
    supported: !1,
    configurations: r,
    decodingInfoResults: [],
    error: d
  }));
}
function Io(n) {
  var t;
  const e = (t = n.videoCodec) == null ? void 0 : t.split(","), i = ar(n), s = n.width || 640, r = n.height || 480, a = n.frameRate || 30, o = n.videoRange.toLowerCase();
  return e ? e.map((u) => {
    const l = {
      contentType: Xt($r(u), "video"),
      width: s,
      height: r,
      bitrate: i,
      framerate: a
    };
    return o !== "sdr" && (l.transferFunction = o), l;
  }) : [];
}
function Do(n, t, e) {
  var i;
  const s = (i = n.audioCodec) == null ? void 0 : i.split(","), r = ar(n);
  return s && n.audioGroups ? n.audioGroups.reduce((a, o) => {
    var u;
    const l = o ? (u = t.groups[o]) == null ? void 0 : u.tracks : null;
    return l ? l.reduce((d, h) => {
      if (h.groupId === o) {
        const c = parseFloat(h.channels || "");
        s.forEach((f) => {
          const g = {
            contentType: Xt(f, "audio"),
            bitrate: e ? Co(f, r) : r
          };
          c && (g.channels = "" + c), d.push(g);
        });
      }
      return d;
    }, a) : a;
  }, []) : [];
}
function Co(n, t) {
  if (t <= 1)
    return 1;
  let e = 128e3;
  return n === "ec-3" ? e = 768e3 : n === "ac-3" && (e = 64e4), Math.min(t / 2, e);
}
function ar(n) {
  return Math.ceil(Math.max(n.bitrate * 0.9, n.averageBitrate) / 1e3) * 1e3 || 1;
}
function _o(n) {
  let t = "";
  const {
    audio: e,
    video: i
  } = n;
  if (i) {
    const s = Ue(i.contentType);
    t += `${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction || "sd"}_${Math.ceil(i.bitrate / 1e5)}`;
  }
  if (e) {
    const s = Ue(e.contentType);
    t += `${i ? "_" : ""}${s}_c${e.channels}`;
  }
  return t;
}
class Ot {
  /**
   * Get the video-dev/hls.js package version.
   */
  static get version() {
    return Zt;
  }
  /**
   * Check if the required MediaSource Extensions are available.
   */
  static isMSESupported() {
    return nr();
  }
  /**
   * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
   */
  static isSupported() {
    return po();
  }
  /**
   * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
   */
  static getMediaSource() {
    return _t();
  }
  static get Events() {
    return E;
  }
  static get MetadataSchema() {
    return dt;
  }
  static get ErrorTypes() {
    return Y;
  }
  static get ErrorDetails() {
    return D;
  }
  /**
   * Get the default configuration applied to new instances.
   */
  static get DefaultConfig() {
    return Ot.defaultConfig ? Ot.defaultConfig : ja;
  }
  /**
   * Replace the default configuration applied to new instances.
   */
  static set DefaultConfig(t) {
    Ot.defaultConfig = t;
  }
  /**
   * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
   * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
   */
  constructor(t = {}) {
    this.config = void 0, this.userConfig = void 0, this.logger = void 0, this.coreComponents = void 0, this.networkControllers = void 0, this._emitter = new Us(), 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 e = this.logger = mr(t.debug || !1, "Hls instance", t.assetPlayerId), i = this.config = za(Ot.DefaultConfig, t, e);
    this.userConfig = t, i.progressive && Xa(i, e);
    const {
      abrController: s,
      bufferController: r,
      capLevelController: a,
      errorController: o,
      fpsController: u
    } = i, l = new o(this), d = this.abrController = new s(this), h = new yn(this), c = i.interstitialsController, f = c ? this.interstitialsController = new c(this, Ot) : null, g = this.bufferController = new r(this, h), p = this.capLevelController = new a(this), m = new u(this), y = new xo(this), T = i.contentSteeringController, v = T ? new T(this) : null, x = this.levelController = new uo(this, v), A = new oo(this), C = new To(this.config, this.logger), S = this.streamController = new yo(this, h, C), R = this.gapController = new to(this, h);
    p.setStreamController(S), m.setStreamController(S);
    const b = [y, x, S];
    f && b.splice(1, 0, f), v && b.splice(1, 0, v), this.networkControllers = b;
    const I = [d, g, R, p, m, A, h];
    this.audioTrackController = this.createController(i.audioTrackController, b);
    const _ = i.audioStreamController;
    _ && b.push(this.audioStreamController = new _(this, h, C)), this.subtitleTrackController = this.createController(i.subtitleTrackController, b);
    const F = i.subtitleStreamController;
    F && b.push(this.subtititleStreamController = new F(this, h, C)), this.createController(i.timelineController, I), C.emeController = this.emeController = this.createController(i.emeController, I), this.cmcdController = this.createController(i.cmcdController, I), this.latencyController = this.createController(lo, I), this.coreComponents = I, b.push(l);
    const $ = l.onErrorOut;
    typeof $ == "function" && this.on(E.ERROR, $, l), this.on(E.MANIFEST_LOADED, y.onManifestLoaded, y);
  }
  createController(t, e) {
    if (t) {
      const i = new t(this);
      return e && e.push(i), i;
    }
    return null;
  }
  // Delegate the EventEmitter through the public API of Hls.js
  on(t, e, i = this) {
    this._emitter.on(t, e, i);
  }
  once(t, e, i = this) {
    this._emitter.once(t, e, i);
  }
  removeAllListeners(t) {
    this._emitter.removeAllListeners(t);
  }
  off(t, e, i = this, s) {
    this._emitter.off(t, e, i, s);
  }
  listeners(t) {
    return this._emitter.listeners(t);
  }
  emit(t, e, i) {
    return this._emitter.emit(t, e, i);
  }
  trigger(t, e) {
    if (this.config.debug)
      return this.emit(t, t, e);
    try {
      return this.emit(t, t, e);
    } catch (i) {
      if (this.logger.error("An internal error happened while handling event " + t + '. Error message: "' + i.message + '". Here is a stacktrace:', i), !this.triggeringException) {
        this.triggeringException = !0;
        const s = t === E.ERROR;
        this.trigger(E.ERROR, {
          type: Y.OTHER_ERROR,
          details: D.INTERNAL_EXCEPTION,
          fatal: s,
          event: t,
          error: i
        }), this.triggeringException = !1;
      }
    }
    return !1;
  }
  listenerCount(t) {
    return this._emitter.listenerCount(t);
  }
  /**
   * Dispose of the instance
   */
  destroy() {
    this.logger.log("destroy"), this.trigger(E.DESTROYING, void 0), this.detachMedia(), this.removeAllListeners(), this._autoLevelCapping = -1, this._url = null, this.networkControllers.forEach((e) => e.destroy()), this.networkControllers.length = 0, this.coreComponents.forEach((e) => e.destroy()), this.coreComponents.length = 0;
    const t = this.config;
    t.xhrSetup = t.fetchSetup = void 0, this.userConfig = null;
  }
  /**
   * Attaches Hls.js to a media element
   */
  attachMedia(t) {
    if (!t || "media" in t && !t.media) {
      const r = new Error(`attachMedia failed: invalid argument (${t})`);
      this.trigger(E.ERROR, {
        type: Y.OTHER_ERROR,
        details: D.ATTACH_MEDIA_ERROR,
        fatal: !0,
        error: r
      });
      return;
    }
    this.logger.log("attachMedia"), this._media && (this.logger.warn("media must be detached before attaching"), this.detachMedia());
    const e = "media" in t, i = e ? t.media : t, s = e ? t : {
      media: i
    };
    this._media = i, this.trigger(E.MEDIA_ATTACHING, s);
  }
  /**
   * Detach Hls.js from the media
   */
  detachMedia() {
    this.logger.log("detachMedia"), this.trigger(E.MEDIA_DETACHING, {}), this._media = null;
  }
  /**
   * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
   */
  transferMedia() {
    this._media = null;
    const t = this.bufferController.transferMedia();
    return this.trigger(E.MEDIA_DETACHING, {
      transferMedia: t
    }), t;
  }
  /**
   * Set the source URL. Can be relative or absolute.
   */
  loadSource(t) {
    this.stopLoad();
    const e = this.media, i = this._url, s = this._url = je.buildAbsoluteURL(self.location.href, t, {
      alwaysNormalize: !0
    });
    this._autoLevelCapping = -1, this._maxHdcpLevel = null, this.logger.log(`loadSource:${s}`), e && i && (i !== s || this.bufferController.hasSourceTypes()) && (this.detachMedia(), this.attachMedia(e)), this.trigger(E.MANIFEST_LOADING, {
      url: t
    });
  }
  /**
   * 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(t = -1, e) {
    this.logger.log(`startLoad(${t + (e ? ", <skip seek to start>" : "")})`), this.started = !0, this.resumeBuffering();
    for (let i = 0; i < this.networkControllers.length && (this.networkControllers[i].startLoad(t, e), !(!this.started || !this.networkControllers)); i++)
      ;
  }
  /**
   * Stop loading of any stream data.
   */
  stopLoad() {
    this.logger.log("stopLoad"), this.started = !1;
    for (let t = 0; t < this.networkControllers.length && (this.networkControllers[t].stopLoad(), !(this.started || !this.networkControllers)); t++)
      ;
  }
  /**
   * 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((t) => {
      t.resumeBuffering && t.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((t) => {
      t.pauseBuffering && t.pauseBuffering();
    }));
  }
  get inFlightFragments() {
    const t = {
      [W.MAIN]: this.streamController.inFlightFrag
    };
    return this.audioStreamController && (t[W.AUDIO] = this.audioStreamController.inFlightFrag), this.subtititleStreamController && (t[W.SUBTITLE] = this.subtititleStreamController.inFlightFrag), t;
  }
  /**
   * 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 t = this._media, e = t?.currentTime;
    this.detachMedia(), t && (this.attachMedia(t), e && this.startLoad(e));
  }
  removeLevel(t) {
    this.levelController.removeLevel(t);
  }
  /**
   * @returns a UUID for this player instance
   */
  get sessionId() {
    let t = this._sessionId;
    return t || (t = this._sessionId = Gn()), t;
  }
  /**
   * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
   */
  get levels() {
    const t = this.levelController.levels;
    return t || [];
  }
  /**
   * @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(t) {
    this.logger.log(`set currentLevel:${t}`), this.levelController.manualLevel = t, 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(t) {
    this.logger.log(`set nextLevel:${t}`), this.levelController.manualLevel = t, 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(t) {
    this.logger.log(`set loadLevel:${t}`), this.levelController.manualLevel = t;
  }
  /**
   * 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(t) {
    this.levelController.nextLoadLevel = t;
  }
  /**
   * 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(t) {
    this.logger.log(`set firstLevel:${t}`), this.levelController.firstLevel = t;
  }
  /**
   * 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 t = this.levelController.startLevel;
    return t === -1 && this.abrController.forcedAutoLevel > -1 ? this.abrController.forcedAutoLevel : t;
  }
  /**
   * 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(t) {
    this.logger.log(`set startLevel:${t}`), t !== -1 && (t = Math.max(t, this.minAutoLevel)), this.levelController.startLevel = t;
  }
  /**
   * 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(t) {
    const e = !!t;
    e !== this.config.capLevelToPlayerSize && (e ? this.capLevelController.startCapping() : (this.capLevelController.stopCapping(), this.autoLevelCapping = -1, this.streamController.nextLevelSwitch()), this.config.capLevelToPlayerSize = e);
  }
  /**
   * 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: t
    } = this.abrController;
    return t ? t.getEstimate() : NaN;
  }
  set bandwidthEstimate(t) {
    this.abrController.resetEstimator(t);
  }
  get abrEwmaDefaultEstimate() {
    const {
      bwEstimator: t
    } = this.abrController;
    return t ? t.defaultEstimate : NaN;
  }
  /**
   * get time to first byte estimate
   * @type {number}
   */
  get ttfbEstimate() {
    const {
      bwEstimator: t
    } = this.abrController;
    return t ? t.getEstimateTTFB() : NaN;
  }
  /**
   * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
   */
  set autoLevelCapping(t) {
    this._autoLevelCapping !== t && (this.logger.log(`set autoLevelCapping:${t}`), this._autoLevelCapping = t, this.levelController.checkMaxAutoUpdated());
  }
  get maxHdcpLevel() {
    return this._maxHdcpLevel;
  }
  set maxHdcpLevel(t) {
    Ur(t) && this._maxHdcpLevel !== t && (this._maxHdcpLevel = t, 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: t,
      config: {
        minAutoBitrate: e
      }
    } = this;
    if (!t) return 0;
    const i = t.length;
    for (let s = 0; s < i; s++)
      if (t[s].maxBitrate >= e)
        return s;
    return 0;
  }
  /**
   * max level selectable in auto mode according to autoLevelCapping
   */
  get maxAutoLevel() {
    const {
      levels: t,
      autoLevelCapping: e,
      maxHdcpLevel: i
    } = this;
    let s;
    if (e === -1 && t != null && t.length ? s = t.length - 1 : s = e, i)
      for (let r = s; r--; ) {
        const a = t[r].attrs["HDCP-LEVEL"];
        if (a && a <= i)
          return r;
      }
    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(t) {
    this.abrController.nextAutoLevel = t;
  }
  /**
   * 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(t) {
    var e;
    return ((e = this.audioTrackController) == null ? void 0 : e.setAudioOption(t)) || 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(t) {
    var e;
    return ((e = this.subtitleTrackController) == null ? void 0 : e.setSubtitleOption(t)) || null;
  }
  /**
   * Get the complete list of audio tracks across all media groups
   */
  get allAudioTracks() {
    const t = this.audioTrackController;
    return t ? t.allAudioTracks : [];
  }
  /**
   * Get the list of selectable audio tracks
   */
  get audioTracks() {
    const t = this.audioTrackController;
    return t ? t.audioTracks : [];
  }
  /**
   * index of the selected audio track (index in audio track lists)
   */
  get audioTrack() {
    const t = this.audioTrackController;
    return t ? t.audioTrack : -1;
  }
  /**
   * selects an audio track, based on its index in audio track lists
   */
  set audioTrack(t) {
    const e = this.audioTrackController;
    e && (e.audioTrack = t);
  }
  /**
   * get the complete list of subtitle tracks across all media groups
   */
  get allSubtitleTracks() {
    const t = this.subtitleTrackController;
    return t ? t.allSubtitleTracks : [];
  }
  /**
   * get alternate subtitle tracks list from playlist
   */
  get subtitleTracks() {
    const t = this.subtitleTrackController;
    return t ? t.subtitleTracks : [];
  }
  /**
   * index of the selected subtitle track (index in subtitle track lists)
   */
  get subtitleTrack() {
    const t = this.subtitleTrackController;
    return t ? t.subtitleTrack : -1;
  }
  get media() {
    return this._media;
  }
  /**
   * select an subtitle track, based on its index in subtitle track lists
   */
  set subtitleTrack(t) {
    const e = this.subtitleTrackController;
    e && (e.subtitleTrack = t);
  }
  /**
   * Whether subtitle display is enabled or not
   */
  get subtitleDisplay() {
    const t = this.subtitleTrackController;
    return t ? t.subtitleDisplay : !1;
  }
  /**
   * Enable/disable subtitle display rendering
   */
  set subtitleDisplay(t) {
    const e = this.subtitleTrackController;
    e && (e.subtitleDisplay = t);
  }
  /**
   * 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(t) {
    this.config.lowLatencyMode = t;
  }
  /**
   * 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(t) {
    this.latencyController.targetLatency = t;
  }
  /**
   * 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(t) {
    this.levelController.pathwayPriority = t;
  }
  /**
   * returns true when all SourceBuffers are buffered to the end
   */
  get bufferedToEnd() {
    var t;
    return !!((t = this.bufferController) != null && t.bufferedToEnd);
  }
  /**
   * returns Interstitials Program Manager
   */
  get interstitialsManager() {
    var t;
    return ((t = this.interstitialsController) == null ? void 0 : t.interstitialsManager) || null;
  }
  /**
   * returns mediaCapabilities.decodingInfo for a variant/rendition
   */
  getMediaDecodingInfo(t, e = this.allAudioTracks) {
    const i = xs(e);
    return bo(t, i, navigator.mediaCapabilities);
  }
}
Ot.defaultConfig = void 0;
Ft.KeySystemFormats;
Ft.KeySystems;
Ft.SubtitleStreamController;
Ft.TimelineController;
Ft.requestMediaKeySystemAccess;
export {
  jr as AbrController,
  it as AttrList,
  Er as AudioStreamController,
  Er as AudioTrackController,
  vn as BasePlaylistController,
  ds as BaseSegment,
  On as BaseStreamController,
  Mn as BufferController,
  Er as CMCDController,
  ei as CapLevelController,
  Ms as ChunkMetadata,
  $n as ContentSteeringController,
  Er as Cues,
  Rs as DateRange,
  Er as EMEController,
  ut as ErrorActionFlags,
  Jr as ErrorController,
  D as ErrorDetails,
  Y as ErrorTypes,
  E as Events,
  Un as FPSController,
  ts as FetchLoader,
  Le as Fragment,
  Ot as Hls,
  ue as HlsSkip,
  pi as HlsUrlParameters,
  Ts as Level,
  an as LevelDetails,
  ye as LevelKey,
  qe as LoadStats,
  Tt as M3U8Parser,
  dt as MetadataSchema,
  at as NetworkErrorAction,
  xr as Part,
  W as PlaylistLevelType,
  Er as SubtitleTrackController,
  sr as XhrLoader,
  Ot as default,
  $a as fetchSupported,
  _t as getMediaSource,
  nr as isMSESupported,
  po as isSupported
};
//# sourceMappingURL=hls.light-B2iPb-fX.js.map